Coroutines

Coroutines allow one to spread the execution of code over multiple frames using the yield statement.

Coroutines are a part of the Unity Engine and not a part of the C# languages. As such you can only start and stop coroutines from the class that inherits from Monobehaviour.

// Coroutines are always of type IEnumerator
IEnumerator Move(Vector3 destination, float speed)
{
    while (transform.position != destination)
    {
        transform.position=Vector3.MoveTowards(transform.position, 
                                               destination, 
                                               speed*Time.deltaTime);
        // yield stops the coroutine for this frame.
        yield return null;
    }
}

Examples

 yield break;

ends the coroutine.


yield return new WaitForSeconds(2);

pauses the coroutine for two seconds.


yield return null;

pauses a coroutine until the next frame started.


yield return StartCoroutine( DoSomething() );

pauses a coroutine until the coroutine DoSomething() has finished running.

To stop a coroutine, you'll need a reference to it to pass into the StopCoroutine() method:

IEnumerator currentCoroutine = DoSomething();
StartCoroutine("currentCoroutine");
StopCoroutine("currentCoroutine");

void Start()
{
    StartCoroutine(CoroutineWithMultipleParameters(1.0F, 2.0F, "foo"));
}

IEnumerator CoroutineWithMultipleParameters(float aNum, float bNum, string aWord) 
{
    //stuff
}

Introduction to Game Development (E21: coroutines) by Sebastian Lague