Mechanics of Coroutines

How does Unity execute the coroutines? I take it that the execution somewhat resembles threading, but I am unclear on what's happening when a coroutine is executed.

Are the coroutines a collection of delegates which, when the IEnumerator gets to that particular delegate, will execute a function?

What happens when the coroutine calls yield? Like, for instance, when it calls "yields return WaitForSeconds()" does the iterator go to the next coroutine or does it wait for that coroutine to finish before going to the next? And, when the coroutine calls "yield break", does it remove that coroutine from the collection of coroutines?

The behavior of Coroutines is more like time slicing than threading as all coroutines are executed from the main thread.

https://docs.unity3d.com/Manual/ExecutionOrder.html

  • yield; The coroutine will continue after all Update functions have been called on the next frame.
  • yield WaitForSeconds(2); Continue after a specified time delay, after all Update functions have been called for the frame
  • yield WaitForFixedUpdate(); Continue after all FixedUpdate has been called on all scripts
  • yield WWW Continue after a WWW download has completed.
  • yield StartCoroutine(MyFunc); Chains the coroutine, and will wait for the MyFunc coroutine to complete first.

Coroutines are reentered at the point where they returned.

I think that is all the public information about Coroutines. It's always safest to avoid making assumptions based on the underlying implementation since it is not public and could therefore change at any time.

More info:

https://docs.unity3d.com/Manual/Coroutines.html

https://docs.unity3d.com/ScriptReference/Coroutine.html