Coroutine Concepts Example

Code

using UnityEngine;
using System.Collections;
using System;
public class CoroutineTest : MonoBehaviour
{
    public void Awake ()
    {
        Log ("Awake");
    }
 
    public void Start ()
    {
        Log ("Start");
        StartCoroutine (CoroutineOne (Time.frameCount));
        StartCoroutine (RunOnceCoroutine ());
    }
 
    public void Update ()
    {
        Log ("Update");
    }
 
    public void LateUpdate ()
    {
        Log ("LateUpdate");
 
        if (Time.frameCount == 2)
        {
            StartCoroutine (CoroutineTwo (Time.frameCount));
        }
    }
 
    public void FixedUpdate ()
    {
        Log ("FixedUpdate");
    }
 
    public IEnumerator CoroutineOne (int startFrame)
    {
        int iteration = 1;
        Debug.Log(String.Format("Coroutine 1 starting in frame {0}.", startFrame));
 
        while (true)
        {
            Debug.Log (String.Format ("Coroutine 1 has iterated {0} times.", iteration++));
            yield return "Anything you want to return because the Unity coroutine hack does not use it.";
        }
    }
 
    public IEnumerator CoroutineTwo (int startFrame)
    {
 
        int iteration = 1;
        Debug.Log(String.Format("Coroutine 2 starting in frame {0}.", startFrame));
 
        while (true)
        {
            Debug.Log (String.Format ("Coroutine 2 has iterated {0} times.", iteration++));
            yield return Mathf.PI;
        }
    }
 
    public IEnumerator RunOnceCoroutine ()
    {
        Debug.Log ("I am a terminating coroutine, I will print this and then become one with the ether.");
        yield return "Like tears in rain";
    }
 
    public static void Log (String method)
    {
        Debug.Log (String.Format ("{0}() - Frame {1}", method, Time.frameCount));
    }
}








Commentary

This is used to demonstrate certain subtle principles and concepts around the usage of Unity coroutines and their execution order in the Unity game engine runtime. It also includes the generated iteration blocks for the interesting parts of the IEnumerable backing the coroutines and the output of the first few frames when executed.

Snippet Usage

Unless otherwise stated, the content of this page is licensed under GNU Free Documentation License.