Coroutine Not Adding Correctly

Hi so im making a coroutine to add stamina while you are under 100 but what happens is it basically just jumps instantly to 100.

 Coroutine:

 IEnumerator gainStamina()
    {
        float timeToGainStamina = 1f;
        while (stamina < maxStamina)
        {
            stamina += 1;
            yield return new WaitForSeconds(timeToGainStamina); 
        }
    }
}
  • In Update:

     StartCoroutine(gainStamina());
    
       if (stamina >= maxStamina)
       {
           stamina = maxStamina;
       }
    

maxStamina = 100 btw

The answer by @IvanC314 is almost correct but will not work. Yes you should start this in Start() or Awake() but at the same time you then have to change this to actually be an endlessly running Coroutine:

 IEnumerator gainStamina()
 {
        //directly creating the WaitForSeconds object reduces memory allocation during runtime:
         var timeToGainStamina = new WaitForSeconds(1f);
         while (true)
         {
             if(stamina >= maxStamina)
             {
                     yield return null; //wait a frame
                     continue; //continue call to skip stamina addition
             }
             stamina += 1;
             yield return timeToGainStamina; 
         }
 }

I think the problem is that you put your StartCoroutine(gainStamina()) in Update so that it repeatedly calls gainStamina() every frame. Try putting it in Start() or Awake() to just call it once.