- Home /
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?
Answer by syclamoth · Oct 10, 2011 at 07:42 AM
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.
Sorry, but where would this go?
I put it in the OnGUI function, and set the GUI colour to currentColor, and I get an error saying to put a semi-colon at the end, even though there is one.
Got rid of that error, and its still not working.
It works, kinda, but doesn't blend the colours. Its green for 100, but as soon as health gets to 99, its red.
Thanks for that!
Ok- you need to turn all your health values into floats! I think it doesn't know what to do with integer division.
Your answer
Follow this Question
Related Questions
How do I make a colour editor UI? 1 Answer
Help with text color 1 Answer
Find brightness of certain part of screen 0 Answers
Get the color under the mouse cursor 2 Answers