Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 783
Ben Hayward Avatar asked May 23 '16 12:05

Ben Hayward


People also ask

Do coroutines automatically stop?

Coroutines are also stopped when the MonoBehaviour is destroyed or if the GameObject the MonoBehaviour is attached to is disabled. Coroutines are not stopped when a MonoBehaviour is disabled. An example of StartCoroutine: using UnityEngine; using System.

Will coroutines run on deactivated objects Unity?

You cannot start a coroutine function from a script that has its GameObject de-activated. The StartCoroutine function is a function under the MonoBehaviour class. When you have to start a coroutine on a deactivated GameObject, you need a reference to a MonoBehaviour object that has an active GameObject.

Can you pause a coroutine?

The informative description below, straight from Unity's documentation, shows that a coroutine can suspend it's execution, until the given yield instruction finishes. Basically, scripts run from top to bottom with no pause, but a coroutine gives the ability to pause and wait for instructions before moving on.

What is coroutine is it running on new thread Unity?

In answer to the question in your title, coroutines DO NOT start a new thread and in themselves have no connection to threads. Don't forget that Unity3D is fundamentally frame based .. MonoBehaviours are a frame based concept. Coroutines - in Unity - are inherently connected to this paradigm.


1 Answers

Short answer:

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

like image 79
Jerry Switalski Avatar answered Sep 19 '22 12:09

Jerry Switalski