Coroutines In Unity3D – The Gritty Details

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:

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!

Advertisements

One thought on “Coroutines In Unity3D – The Gritty Details

  1. Pingback: LoadLevelAsync to make a progress bar / loading screen in Unity3D | the world starts with you

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s