Menu
CoddyTech

Your First Coroutine

Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 24 of 71.

Update() must finish every frame, so it cannot wait. A coroutine can: it is a method that pauses and carries on later, right where it stopped. It returns IEnumerator, which needs using System.Collections;, and each yield return in it is a pause. In C#, yield return makes a method that hands out its values one at a time; Unity asks for the next one when the wait is over. yield return null waits one frame, and yield return new WaitForSeconds(3f) waits 3 seconds.

StartCoroutine(Cycle()) starts one. This traffic light goes green, yellow 3 seconds later, and red after one more second:

using System.Collections;
using UnityEngine;

public class TrafficLight : MonoBehaviour
{
    Renderer lamp;

    void Start()
    {
        lamp = GetComponent<Renderer>();
        StartCoroutine(Cycle());
    }

    IEnumerator Cycle()
    {
        lamp.material.color = Color.green;
        yield return new WaitForSeconds(3f);
        lamp.material.color = Color.yellow;
        yield return new WaitForSeconds(1f);
        lamp.material.color = Color.red;
    }
}

StartCoroutine runs the coroutine up to its first yield at once, then Start() carries on; Unity resumes it after each wait, with its local variables as they were. A bare Cycle(); without StartCoroutine does nothing: it builds the paused method and drops it, and not one line of it runs. And yield return 3f; is not a 3 second wait: Unity only knows wait objects such as WaitForSeconds and treats any other value as one frame.

challenge icon

Challenge

Easy

Make Space spring the spike trap with a coroutine.

  1. Write IEnumerator Spring(): log Click, yield return new WaitForSeconds(0.5f);, then transform.position += Vector3.up;.
  2. Then wait 2 seconds the same way and take Vector3.up away again.
  3. In the Space if, start it with StartCoroutine(Spring());.

Press Play and press Space: the spikes jump up, then sink. Then Check.

Try it yourself

using System.Collections;
using UnityEngine;

public class SpikeTrap : MonoBehaviour
{
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            // Spring the trap with a coroutine
        }
    }

    // IEnumerator Spring(): Click, wait 0.5 s, up 1 unit, wait 2 s, down 1 unit
}

All lessons in Physics and Gameplay

Practice on your own: Unity playground