Health bar slow drain effect

I’m trying to make a health bar for a 2d platformer. I followed a Brackey’s tutorial, and it works perfectly. The problem is that I wanted to make it with a certain effect when the player takes damage, and I don’t know how to do that with a slider (what he uses in the tutorial).

The effect is that when the player takes damage a portion of the red bar should turn white, as to show how much life it removed, then, that white portion of the red bar should slowly drain from right to left until completely disappearing and just having red again.

I had an idea on how to do it, but I read the documentation of the sliders and I don’t know how to implement it. Here is my code:

[Space]
    [Header("Health bar")]
    public Slider slider;
   
    public void SetMaxHealth(float health)
    {
        slider.maxValue = health;
        slider.value = health;
    }

    public void SetHealth(float health)
    {
        slider.value = health;

        //if the white bar lenght is minor than the red bar lenght
        //{
        //    then slowly decrease the white bar lenght
        //}
        //else
        //{
        //    else, don't decrease the white bar lenght
        //}
    }

If anyone has an idea on how to do this with a slider or if I should use other thing, I appreciate it.

Simplest answer: Create an Update method and a “targetValue” field. When you receive SetHealth, you’ll set targetValue instead of the slider, and Update() will set the value of the slider until it matches targetValue. (Probably using Mathf.MoveTowards)

To do the red-white thing, you’ll need two sliders, red in front of white. Set the red one’s value directly (like you’re doing now), and use the delayed-setting method described above to set the white one.

2 Likes

Worked perfectly, thanks!