In my last post I talked about why some code is easier to write, read and maintain in Unity 3D when it’s written using coroutines, and touched on how Unity3D uses C# iterators to implement them. Now let’s look at how Unity3D makes these work as coroutines.
With iterators your code is responsible for creating an iterator and causing the iterator code to continue after a yield statement, such as using foreach in the MSDN example. In Unity’s world coroutines work if you are a class derived from MonoBehaviour. This class has a function StartCoroutine() which can start any function which returns IEnumerator as a coroutine.
Coroutines aren’t very useful until they include a yield statement. Unity uses the values returned by yield as scheduling information – to decide when to call the next portion of the coroutine. I’ve never found a complete list of acceptable return values from yield for Unity3D. Here’s the ones I know about:
- yield break; // exit the coroutine completely
- yield return null; // wait one frame
- yield return StartCoroutine(<coroutine-function>); // wait until <coroutine-function> exits
- yield return new WaitForFixedUpdate(); // wait until next fixed update
- yield return new WaitForSeconds(2); // wait for 2 seconds
- yield return Application.LoadLevelAsync(levelName); // wait until level load
- yield return Resources.UnloadUnusedAssets(); // wait until unload complete
- yield return new WWW(url); // wait for download to complete
It’s not multithreading!
There’s no multi-threading going on here. All scripts in Unity are called on a single thread, so no locking of variables is required. However other scripts may change global or object state between function calls or across a yield instruction. At times it becomes important to know when during a frame the coroutine will be executed. The overall execution order documentation says:
- Most coroutines run after Update() and before LateUpdate()
- Coroutines started from LateUpdate() run after LateUpdate()
- return yield new WaitForFixedUpdate() // causes a coroutine to run after the next FixedUpdate()
As a final complication StartCoroutine() causes the coroutine to run immediately, until its first yield.
That All Sounds Hard
It’s not. I’ve dug in here, and documented all the gritty details. 90% of the time you don’t need these details at all. Looking at my coroutines they are almost all using
- yield break;
- yield return null;
- yield return StartCoroutine().
What are you waiting for? If it sounds like coroutines will solve a problem for you – try them out!