Fancy Health Bar

I decided to get fancy with the health bars. Just like you see in other games, as the health passes below certain thresholds the color changes from Green (healthy) to Yellow (damaged) to Red (critical). While typing this I realized I should make the thresholds as serilizedfields and then it can be set from the editor. Changes to be made after the post.

private void HandleHealthChanged(int oldHealth, int newHealth) {
float fillAmount = (float) newHealth / health.MaxHealth;
healthBarImage.fillAmount = fillAmount;

    if (fillAmount > 0.6f) { healthBarImage.color = new Color32(10,130,10,255);}
        else if (fillAmount < 0.2f) { healthBarImage.color = new Color32(180,20,10,255);}
            else { healthBarImage.color = new Color32(190,170,10,255);}
}

image

1 Like

Now the color change is adjustable from the editor.

image

Nice! I do this often. Here’s a little tip;
Use a Gradient with red on the left and green on the right (and yellow in the middle if you don’t want the ugly brown). You can even change ‘Mode’ from Blend to Fixed and use the thresholds you specified above
Blended
image

Fixed
image

[SerializeField] Gradient healthColor;

private void HandleHealthChanged(int oldHealth, int newHealth)
{
    float fillAmount = (float) newHealth / health.MaxHealth;
    healthBarImage.fillAmount = fillAmount;
    healthBarImage.color = healthColor.Evaluate(fillAmount);
}

healthColor.Evaluate will return the color that corresponds to the fillAmount. This allows you to adjust not only the thresholds but also the color, and it’s all wrapped up in a neat little box

2 Likes

This is something that I was discussing with a Coworker today about making it a gradient. If you don’t like the brownish color you can also add another point to route around the color you don’t like. The next step would be to adjust those gradient colors and the points they change at as a serilizedfield.

Yes, all of this is in my post: Gradient with no brown, and it’s a serialized field

1 Like

Privacy & Terms