Decrease a gauge with IEnumerator / Lerp ?

Hello guys,

I’m stuck since a too long time on the polishing of my gauge management.
I’ve a scrollbar which I use to represent the life of my Hero : when he becomes hurted, I I called a fonction which calls an IEnumerator which progressively decrease the life amaount and the gauge. But the fact is that when monsters trigger the event before the end of another instance of the enumerator, results become weird.
I’ve wanted to try with a lerp but I’m not convinced by the result, do you have any ideas to improve my code ?

public void SetDamage(float damage)
{
    StopCoroutine("ChangeLifeBar");
      if (lifeBar_is_ok)
      {
          StartCoroutine(ChangeLifeBar(damage));
      }
}

IEnumerator ChangeLifeBar(float damage)
    {
        float futureLife = life - damage;
        lifeBar_is_ok = false;
        while (!lifeBar_is_ok)
        {
            life--;
            hero_life_bar.size = life / 100f;
            lifeBar_is_ok = futureLife == life;
            yield return null;
        }
    }

Thanks !

The solution would be to have a global target value which represents the current state of the health. This target gets updated when the player gets hurt so the lerping only considers the current value.

You only triggers the coroutine if it is not already running.

 private float currentHealth = 100f;
 public void SetDamage(float damage) {
    currentHealth -= damage;
    if(isRunning == false)
           StartCoroutine(ChangeLifeBar(damage));    
 }

 IEnumerator ChangeLifeBar(float damage)
 {
     isRunning = true;   
   
     while (Mathf.Approximately(gaugeLevel, currentHealth) == false)
     {
         gaugeLevel = Mathf.MoveTowards(gaugeLevel, currentHealth, step *Time.deltaTime);
         yield return null;
     }
     isRunning = false;
 }

EDIT: Comment button is gone (??!!) so yes you should, I edited the answer.