Coroutines, Coroutines, Coroutines


Whether crafting fluid AI routines or just fading out a screen coroutines can provide a useful tool to any coder wanting to complete an action (or series of actions) across a number of frames. Coroutines are explained on the Script Reference Example quite well but wanted to highlight a few features so decided to include a demonstration below;

using UnityEngine;
using System.Collections;
public class CoroutineDemoClass : MonoBehaviour
{
    public float MoveSpeed = 0.5f;
    public float WaitPeriod = 0.1f;
     
    public void Awake() 
    {
        Debug.Log("Started Walking");
        StartCoroutine(Walk());
    }

    public IEnumerator Walk() 
    {
        //Always quantify a loop with a valid exit condition 
        //(at worst enabled status of the component)
        while (this.enabled) 
        {
            //movement actions (especially physics based movement) 
            //should be completed during fixed update
            yield return new WaitForFixedUpdate();
            //move forward
            transform.Translate(transform.forward * MoveSpeed);
            //wait for a period of time.
            yield return new WaitForSeconds(WaitPeriod);
        }
        Debug.Log("Stopped. Walking... Disabled");
        yield return null;
    }
}

This simple MonoBehaviour moves the GameObject it is attached to  X amount forward every N seconds. This example is overly simplistic but should highlight the value of using coroutines.

This coroutine was initiated by directly calling the routine meaning there is no way to stop the Walk function from outside of the routine. Here only disabling the component would stop the behaviour "walking". 

All coroutines can be stopped at anytime using the StopAllCoroutines() function. However to stop an indivdual routine you need to initialise the coroutine differently.

        
        StartCoroutine("Walk");
 




Changing this one line of code will have a cost associated it with it, as the string name needs to be resolved on the component you are calling. However you can now use the Stop Coroutine features to halt a single coroutine at anytime, provide it was started this way, even from outside the component itself.

        
        GameObjectName.StopCoroutine("Walk");




Nesting Coroutines or Parallel Coroutines used in conjunction with callback delegates can make AI and other complex systems much simpler to build and more cost effective than using update when implemented correctly.