Pierre Gravelle Pierre Gravelle - 4 months ago 27
C# Question

Unity - How do I turn the screen red as my character's health gets low?

So I'm working on a Unity C# script for school that's supposed to fade the screen red depending on the player's current health, however I'm having problems with it.

I have a reference to the image component (which is found on the game object this script is attached to), and as the player's health reaches lower levels the alpha is increased.

Here's what I've already tried:


  • Using MonoDevelop to check the bloodLossAlpha and healthSlider.value (values were correctly set)

  • Creating a UI Image game object instead of using a component, then modified the code to search for a game object with a custom tag instead of searching for a component.



I was wondering if someone could please tell me what I'm doing incorrectly.

Slider healthSlider;
Image bloodLossImage;
float bloodLossAlpha;

// Use this for initialization
void Start () {
bloodLossImage = GetComponent<Image>();
healthSlider = GetComponentInChildren<Slider>();
bloodLossAlpha = bloodLossImage.color.a;
}

// Update is called once per frame
void Update () {

float currentHealth = healthSlider.value;

if (currentHealth <= 100 && currentHealth >= 76)
{
bloodLossAlpha = 0f;
}
else if (currentHealth <= 75 && currentHealth >= 51)
{
bloodLossAlpha = 47f;
}
else if (currentHealth <= 50 && currentHealth >= 26)
{
bloodLossAlpha = 94f;
}
else
{
bloodLossAlpha = 141f;
}
}

Answer

I don't have access to your scene and so your currentHealth variable but the fade animation worked for me so hopefully this will give you a good starting point @PierreGravelle. My code:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class test : MonoBehaviour {

// Update is called once per frame
void Update () {
    Color img = gameObject.GetComponent<Image> ().color;
    img.b = Mathf.Lerp (img.b, 0, Time.deltaTime);
    img.g = Mathf.Lerp (img.g, 0, Time.deltaTime);
    gameObject.GetComponent<Image> ().color = img;
    }
}

The mathf.lerp lines are interpolating between img.b or g and 0 by a factor of Time.DeltaTime. I used this code on a canvas image to test. That error you recieved was because you didn't have a Color variable so it wouldn't let you access the color. Instead by adding the Color img and updating that once we made our changes, we can make certain that the color will update.