Hi everyone, I’m trying to build a health bar that lerps between three colors based on the halfway point… I used two lerps that runs based on if it has passed the halfway point. But it isn’t working as it is looking at the whole health bar rather than the halfway points. Any help would be appreciated.
You don’t necessarily have to use Lerps between pairs of colors - you could use one Gradient instead. That way you can easily lerp between 0-1 while showing any color from gradient.
Then do a call to method that can be something like this:
Color ColorFromGradient (float value) // float between 0-1
{
return gradient.Evaluate(value);
}
You can define your gradient to have same colors you have now, either from code or by setting the colors of the gradient from inspector. The simplest way is to use inspector, just create public field and change the colors:
the answer by @eses is definitely the one to use here. it’s general-purpose and involves way less code to maintain. plus it will easily enable fancier gradients, like if you wanted to transition from green to white when health is above 95% or something.
however, for the Lerp()-curious,
the reason your code is not behaving the way you want is that Lerp() needs a value between 0 and 1,
but you’re giving it values between 0 and 0.5 for the red → yellow case, and 0.5 to 1.0 for the yellow → green case.
for the red->yellow case, you should multiply by 2.0.
for the yellow->green case, you should first subtract 0.5 and then multiply by 2.0.
a couple other unrelated notes:
1- i would suggest calculating a value like “normalizedHealth” in front of all your code - normalizedHealth = hpCurrent / hpMax. then use that for if if() statement and the math in the lerp()s. This small extra step will make your code a lot easier to debug / maintain.
2- assuming healthBar is a Unity.Engine.UI.Slider, there’s no need to cast Value or MaxValue to floats. they’re already floats. (but again, i recommend not referencing those values, in favor of a single ‘normalizedHealth’ value)
3- even if you did need to cast value and maxValue to floats, there would be no need to include that additional cast on (float)value/(float)maxValue. division of a float by a float will result in a float.
Love the Gradient since it is flexible, but if you want to do a simple C# line you can go from green-yellow-red like this (s is a float value between 0 and 1):