Coroutines in Unity3d (C# version)

Coroutines in C# work the same way that they do in Javascript (UnityScript), the only difference is that they require more typing (they have a slightly more complicated syntax). You should see the blog post on Javascript coroutines first.

Here, I present the differences:

Coroutines must have the IEnumerator return type:

IEnumerator MyCoroutine()
{
	//This is a coroutine
}

To invoke a coroutine you must do it using the StartCoroutine method:

public class MyScript : MonoBehaviour
{
    void Start()
    {
		StartCoroutine(MyCoroutine());
    }

    IEnumerator MyCoroutine()
    {
        //This is a coroutine
    }
}

The yield statement becomes yield return in C# :

IEnumerator MyCoroutine()
{
    DoSomething();
    yield return 0;	//Wait one frame, the 0 here is only because we need to return an IEnumerable
    DoSomethingElse();
}

Remember that we need to return an IEnumerable, so the Javascript yield; becomes yield return 0; in C#

Also, since C# requires you to use the new operator to create objects, if you want to use WaitForSeconds you have to use it like this:

IEnumerator MyCoroutine()
{
    DoSomething();
    yield return new WaitForSeconds(2.0f);	//Wait 2 seconds
    DoSomethingElse();
}

Happy coroutining :)

About sethillgard

Game developer. Founder of Silent Kraken.
This entry was posted in Programming and tagged , , , , . Bookmark the permalink.
  • So how do you create a coroutine that returns a value at the end?
  • Thanks Seth for sharing these basics. Definitely useful to those looking to learn.

    One note: I had heard that returning null is ever so slightly faster than returning 0 when yielding in a coroutine due to the allocation for creating a new variable :)
blog comments powered by Disqus