Stop coroutine including nested couroutines

StopCoroutine doesn’t seem to stop nested coroutines. For example:

using UnityEngine;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour
{
    private void Start()
    {
        StartCoroutine("Parent");
    }
  
    private void Update()
    {
        if (Input.GetKeyUp(KeyCode.S))
        {
            Debug.Log(Time.frameCount + " stop");

            StopCoroutine("Parent");
        }
    }

    private IEnumerator Parent()
    {
        while (true)
        {
            yield return StartCoroutine("Child");
        }
    }

    private IEnumerator Child()
    {
        yield return new WaitForSeconds(1);

        Debug.Log(Time.frameCount + " test");
    }
}

Since the Child coroutine was started from Parent I would expect that stopping Parent would also stop Child. However, it seems that Child continues to run until it’s done.

Is there any (nice) way to stop nested coroutines?

StopAllCoroutines?

Unity - Scripting API: MonoBehaviour.StopAllCoroutines :slight_smile:

StopAllCoroutines would work in this example but there are situations where I’m running multiple coroutines on an object and I don’t want to stop all of them. I want to stop a specific coroutine and any nested coroutines it started.

I’m pretty sure the answer is that it can’t be done (at least not with any built-in APIs). Maybe this is more of a feature request. :slight_smile:

Necro, but for anyone looking for that:
You can save IEnumerators and stop them manually like so:

        IEnumerator curCo = null;

        public void FadeOutAndDisable()
        {
            if (!gameObject.activeInHierarchy) return; // already disabled

            if (curCo != null)
            {
                StopCoroutine(curCo);
            }
            curCo = CoFadeOut();
            StartCoroutine(curCo);

        }

It depends on your setup. You should maintain the flow if your script. If you got a coroutine starting, let it create a list to store all the others. Thats what a built in thing would do. But as it is content/script architecture related, it is not :wink:

What if you maintain a reference to your coroutines and manage them with the hierarchy you want?

Unity handles this for you from a while back if you just yield the child IEnumerator (do not call Start corotine just yield the enumerator)

3 Likes

@AndersMalmgren
How does this work?
Will it actually start the child Coroutine?
Could you give an example?

Yes unity will do an internal StartCorotuine

@AndersMalmgren Did you find it anywhere in the docs? If so provide me with some links, please :slight_smile:

No, I just tried it and it worked :smile:

2 Likes