Menu
CoddyTech

Loops in Coroutines

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

A loop with a yield return inside runs over many frames, because every pass pauses before the next. With WaitForSeconds the loop repeats something on a beat. This siren flashes 3 times:

IEnumerator Flash()
{
    for (int i = 0; i < 3; i++)
    {
        lamp.enabled = true;
        yield return new WaitForSeconds(0.2f);
        lamp.enabled = false;
        yield return new WaitForSeconds(0.2f);
    }
}

With yield return null the loop does a little every frame until its condition is met, which is how a coroutine animates something. This balloon, at a scale of 1, grows by 0.5 a second until its scale reaches 2, then reports:

IEnumerator Inflate()
{
    while (transform.localScale.x < 2f)
    {
        transform.localScale += Vector3.one * 0.5f * Time.deltaTime;
        yield return null;
    }
    Debug.Log("Full");
}

Time.deltaTime works here as in Update(): the coroutine resumes once per frame, and the line after the loop runs only when the loop is done. Without the yield, the whole loop runs inside one frame and the balloon is full at once. A while (true) loop is fine in a coroutine as long as it yields on every pass; without a yield it never gives the frame back, and the Unity editor freezes.

challenge icon

Challenge

Easy

Space starts the Ride coroutine of the castle's Portcullis. Write Ride so the gate makes one full trip:

  • It rises height (3) units at speed (1.5) units per second, stops exactly at the top and logs Open.
  • It stays open for 1 second.
  • It goes back down at the same speed to where it started (down) and logs Closed.

Press Play and press Space, then Check.

Try it yourself

using System.Collections;
using UnityEngine;

public class Portcullis : MonoBehaviour
{
    public float speed = 1.5f;
    public float height = 3f;
    Vector3 down;

    void Start()
    {
        down = transform.position;
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            StartCoroutine(Ride());
        }
    }

    IEnumerator Ride()
    {
        // Rise height units at speed and log Open, stay 1 second, go back down and log Closed
        yield return null;
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Physics and Gameplay