IEnumerator not iterating correctly

I’m really new at coding and making games and i’m trying to implement a stamina bar into my game but instead of the stamina bar refilling over time it simply goes back up to it’s maximum value after waiting for 2 seconds. Can anyone help?

public class StaminaBar : MonoBehaviour
{
    [Range(0, 1)]
    public float stamina = 1f;
    public float staminaDrain = 0.003f;
    public float staminaGain = 0.003f;
    public float maxStamina = 1f;
    private static Coroutine regen;

    public Image barFill;

    public void Sprint()
    {
        if (stamina - staminaDrain >= 0)
        {
            stamina -= staminaDrain;

            if (regen != null)
                StopCoroutine(regen);

            regen = StartCoroutine(RegenStamina());
        }
    }

    private void Update()
    {
        barFill.fillAmount = stamina;
    }


    private IEnumerator RegenStamina()
    {
        yield return new WaitForSeconds(2);

        while (stamina < maxStamina)
        {
            stamina += staminaGain;
            barFill.fillAmount = stamina;
        }
        regen = null;
    }
}

Hello.

“simply goes back up to it’s maximum value after waiting for 2 seconds”

Yes, its what your code does.

You need to place a yield command inside the while. If not, The while commands are executed all in same frame until (stamina < maxStamina)

You want to stop “thinking” at least once/frame while iterating instde the while, so, you must:

while (stamina < maxStamina)
         {
             yield return null;    // <- This line says "wait 1 frame before continue"
             stamina += staminaGain;
             barFill.fillAmount = stamina;
         }

If you see it still regen too fast, you could wait more frames, or wait some seconds.

 while (stamina < maxStamina)
             {
                 yield return null;
                 yield return null;
                 yield return null;
                 yield return null;
                 stamina += staminaGain;
                 barFill.fillAmount = stamina;
             }

BYE!