GUI Colour based on Health?

Hey all,

I’m having some problems with my GUI. I have a health value displayed on screen, as a number out of 100 (“Health / 100” is displayed). When the health is high, I want the text to be coloured green. As it gets lower, I want it to get redder.

I have a script that I thought should work, but being new to Untiy and Java, it doesn’t. It just is black no matter what. Can anyone help?

Heres the script that I’m using for health and the health display:

var health : int = 100;
var Player : Transform;
var labelPos : Rect = Rect(20,10,300,50);
var Skin : GUISkin;
private var damage : int;
private var damageRed : int;
var Sound : GameObject;
private var HColor = Color(1,1,1,1);
private var Red : float;
private var Green : float;

function Start () {
	health = PlayerPrefs.GetInt("Health");
	SaveHealth ();
}

function Update () {
	OnGUI ();
	ApplyPDamage (damage);
	Green = health/100;                         //Here is colour values for red and green are worked out.
	Red = 1 - Green;                            //I think this is where the problem is
}

function OnGUI () {                            //Here is where the health is displayed
	HColor = Color(Red, Green, 0, 1);
	GUI.color = HColor;
  	GUI.skin = Skin;
  	GUI.Label(labelPos, "Health: " + health + " / 100");
}

function ApplyPDamage (damage : int) {
    health -= damage;
    if(health <= 0) {
        Die();
    }
	HurtSound();
	SaveHealth();
}

function Die () {
	Application.LoadLevel(1);
}

function HurtSound () {
    sound = Sound.GetComponent(AudioSource);
    sound.enabled = true;
    yield WaitForSeconds(1);
    sound.enabled = false;
}

function SaveHealth () {
	PlayerPrefs.SetInt("Health", health);
}

Thanks in advance,
Geko_X

PS: Is this the best way to do it, or is there another way?

Instead of doing something like that, use Color.Lerp!

var healthProportion : float = health / 100;
Color currentColor = Color.Lerp(Color.Red, Color.Green, healthProportion);

That should give you the correct value.