C# for Unity: Coroutines & Multiplayer Networking

Lesson 2 of 7

Coroutines and IEnumerator

A regular method runs to completion within a single frame. A coroutine can pause itself and resume later, spread across multiple frames, without blocking the main thread. Unity coroutines are built on C#'s IEnumerator.

using System.Collections;
using UnityEngine;

public class FadeIn : MonoBehaviour
{
    void Start()
    {
        StartCoroutine(Fade());
    }

    IEnumerator Fade()
    {
        CanvasGroup group = GetComponent<CanvasGroup>();
        float t = 0f;
        while (t < 1f)
        {
            t += Time.deltaTime;
            group.alpha = t;
            yield return null; // pause until next frame
        }
    }
}

The pieces

  • A coroutine is any method that returns IEnumerator and contains at least one yield return.
  • StartCoroutine(...) begins running it, Unity resumes it each frame from wherever it last yield returned.
  • yield return null pauses for exactly one frame.
  • yield return new WaitForSeconds(2f) pauses for 2 (scaled) seconds.

Why not just Update()?

Update() runs every frame for the entire lifetime of the object. A coroutine only runs while it has work to do, then finishes, better for one-off timed sequences like fades, delays, or spawn waves.

📝 Coroutines Quiz

Passing score: 70%
  1. 1.What return type must a coroutine method have?

  2. 2.____(...) is the method you call to begin running a coroutine.

  3. 3.yield return null pauses a coroutine for exactly one frame.