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.
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.
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.
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.
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.
Short answer:
Yes, they will be terminated as Coroutine
s run depending on MonoBehaviour
they were started on. No MonoBehaviour
== No Coroutine
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With