- Home /
Fading Sprite Color According to Value
Hello. I am having trouble with my script, I would like my Hunger/Thirst icon to fade from colors (Green to Yellow to Red) according to how much Food / Drink I have left. Here is my script:
#pragma strict
var Meat:UnityEngine.UI.Image;
var WaterDrop:UnityEngine.UI.Image;
var hungerColor: Color = Color.green;
var thirstColor: Color = Color.green;
var health = 100.0;
var hunger = 100.0;
var hungerSpeed = .1;
var thirst = 100.0;
var thirstSpeed = .2;
function Update ()
{
if ( hunger >= 50.0f)
{
// While hunger value decreases (to 50%), add more red until you get yellow color (1,1,0)
hungerColor.r = 2.0f - ( 2.0f * hunger)/100.0f;
}
else if ( hunger > 0.0f) // don't go below zero
{
// Hunger value is below 50%, remove green component from color until you get red (1,0,0)
hungerColor.g = 2.0f * hunger / 100.0f;
}
Meat.color = hungerColor;
if ( thirst >= 50.0f)
{
// While hunger value decreases (to 50%), add more red until you get yellow color (1,1,0)
thirstColor.r = 2.0f - ( 2.0f * hunger)/100.0f;
}
else if ( thirst > 0.0f) // don't go below zero
{
// Hunger value is below 50%, remove green component from color until you get red (1,0,0)
thirstColor.g = 2.0f * hunger / 100.0f;
}
WaterDrop.color = hungerColor;
hunger -= Time.deltaTime * hungerSpeed;
thirst -= Time.deltaTime * thirstSpeed;
}
Now what happens is both the icons change color at the same time, even though their values are different and also they won't change color back again if I add to the Hunger value or Thirst value. Any help is appreciated. Thank You.
Reason for changing both at the same time: line 44
WaterDrop.color = hungerColor;
should be thirstColor
;
You should stop decreasing hunger and thirst values if they are below zero (set them to 0). If you don't do this, adding to their values probably won't work as they are still below zero. (for example if hunger is decreased to -20.0f and you add only 10.0f)
Thank you, everything is working as it should! Thank you so much. Cheers
Your answer
![](https://koobas.hobune.stream/wayback/20220612073220im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Can't change Alpha value of Image color 1 Answer
How to change Menu Buttons to a Selected Image and Deselected Image 2 Answers
text and image prefab not popping up when set.active 2 Answers
Pixel Perfection unity UI 0 Answers
How to change Image on button click in a prefab that is instantiated 1 Answer