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 🙂