- Home /
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?
Answer by _Petroz · Dec 04, 2010 at 09:35 PM
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:
yield is a C# keyword, documented here -- http://msdn.microsoft.com/en-us/library/9k7k7cf0(VS.80).aspx. Basically the IEnumerator / yield return construct used for coroutines means the Unity engine can iterate over the multiple results returned by the coroutine.
Thanks @_Petroz !! I did not know you could chain coroutines and this is exactly what I needed!
first 2 links are broken by now. First link is now https://docs.unity3d.com/$$anonymous$$anual/ExecutionOrder.html
Your answer
Follow this Question
Related Questions
Collection Change During Iteration 0 Answers
Bullet Script 2 Answers
yield return null vs yield return WaitForEndOfFrame 4 Answers
Can you check a boolean in a coroutine? 2 Answers
application loadlevel c# calling coroutine not working? 1 Answer