StopCoroutine

What if I just wanted to stop that one Coroutine? I tried it and it seems to just keep updating the first Stamina back to being full.

    if (CurrentStamina < maxStamina)
    {
        //StopAllCoroutines();
        StopCoroutine(RefreshStaminaRoutine());
        StartCoroutine(RefreshStaminaRoutine());
    }

To single out a single Coroutine for stopping, you have to prepare a bit in advance by caching the result from StartCoroutine (even though the coroutine itself is an IEnumerator, StartCoroutine returns a Coroutine)

Coroutine refreshRoutine;

and in your method:

if (CurrentStamina<maxStamina)
{
    if(refreshRoutine!=null) StopCoroutine(refreshRoutine);
    refreshRoutine = StartCoroutine(RefreshStaminaRoutine());
}
1 Like

I think I have it working but I don’t know why it works.

At the top I have this:
private Coroutine refreshRoutine;

in my code I have this:

    if (CurrentStamina < maxStamina)
    {
        if (refreshRoutine != null)
        {
            StopCoroutine(RefreshStaminaRoutine());
        }
        else
        {
            refreshRoutine =  StartCoroutine(RefreshStaminaRoutine());
        }
   }

So, am I to assume that the refreshRoutine is checking any Coroutine? and if ther eis one then stop the RefreshStaminaRoutine()?

Why not simply use StopCoroutine(refreshRoutine), because this is the specific instance of the routine you want to stop?

Historically, your original construction worked, but for some reason it wasn’t working, which is why we cached the routine in the first place. My assumpion was that Unity had made a change, and that it was now required to hold a direct reference (which is what Unity has always recommended).

In short, StopCoroutine(RefreshStaminaRoutine()) should have worked in the first place. If it wasn’t working before, I cannot in any way whatsoever explain why your revised method works at all.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms