Ben Hayward
Ben Hayward

Reputation: 1512

Unity: Are running Coroutines destroyed upon loading new scene?

If you have a coroutine running in a script attached to an object in a given scene, when that scene ends, does the coroutine get terminated/destroyed? ...even if the coroutine contains e.g. an endless While loop?


For instance, if I have the following coroutine attached to an object in my scene:

IEnumerator SampleCoroutine()
{
    while (true) {
        yield return new WaitForSeconds(1.0f);
    }
    yield return null;
}

...when a new scene is loaded, assuming no script attached to the object contains "DontDestroyOnLoad(...)", will the coroutine still execute in the newly loaded scene?

Reason for asking: I need to know whether I need to keep a list of all active Coroutines, so that I can end them after every scene change. I don't want performance to degrade as more scenes are used.

Upvotes: 7

Views: 6017

Answers (1)

Jerry Switalski
Jerry Switalski

Reputation: 2720

Short answer:

Yes, they will be terminated as Coroutines run depending on MonoBehaviour they were started on. No MonoBehaviour == No Coroutine.

Upvotes: 9

Related Questions