Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

C# Dictionary

  1. Home
  2. C# Dictionary
  3. Coroutine / IEnumerator

Coroutine / IEnumerator

How to use coroutines in Unity to split processing across frames. Define a method that returns an IEnumerator and start it with StartCoroutine().

Syntax

using System.Collections;
using UnityEngine;

// A method that returns IEnumerator is the body of a coroutine.
IEnumerator CoroutineName()
{
    // Pause execution and return control to the next frame.
    yield return null;

    // Wait for the specified number of seconds.
    yield return new WaitForSeconds(float seconds);

    // Wait until the next FixedUpdate.
    yield return new WaitForFixedUpdate();

    // Wait until the condition becomes true.
    yield return new WaitUntil(() => condition);
}

// Start the coroutine.
Coroutine handle = StartCoroutine(CoroutineName());

// Stop the coroutine.
StopCoroutine(handle);

// Stop all coroutines running on this GameObject.
StopAllCoroutines();

Method List

Method / ClassDescription
StartCoroutine(IEnumerator)Starts a coroutine. Storing the returned Coroutine handle lets you stop it later.
StopCoroutine(Coroutine)Stops the specified coroutine. Pass the value returned by StartCoroutine().
StopAllCoroutines()Stops all coroutines running on this component.
yield return nullPauses execution until the next frame.
yield return new WaitForSeconds(t)Pauses execution for t seconds. Affected by Time.timeScale.
yield return new WaitForSecondsRealtime(t)Pauses execution for t seconds in real time. Not affected by Time.timeScale (continues during pause).
yield return new WaitUntil(() => condition)Waits every frame until the condition becomes true.
yield return new WaitForFixedUpdate()Waits until the next FixedUpdate. Use this to synchronize with physics.

Sample Code

using System.Collections;
using UnityEngine;

public class CoroutineSample : MonoBehaviour
{
    private Coroutine blinkCoroutine;

    void Start()
    {
        // Start a coroutine.
        StartCoroutine(Countdown(5));

        // Store the handle so it can be stopped later.
        blinkCoroutine = StartCoroutine(Blink(0.5f));

        // Stop the blinking after 3 seconds.
        StartCoroutine(DelayedAction(3f, () =>
        {
            StopCoroutine(blinkCoroutine);
            Debug.Log("Blinking stopped.");
        }));
    }

    // A coroutine that counts down.
    IEnumerator Countdown(int seconds)
    {
        for (int i = seconds; i > 0; i--)
        {
            Debug.Log($"Countdown: {i}");
            yield return new WaitForSeconds(1f); // Wait 1 second.
        }
        Debug.Log("Go!");
    }

    // A coroutine that blinks the object.
    IEnumerator Blink(float interval)
    {
        Renderer renderer = GetComponent<Renderer>();
        while (true) // Stopped externally via StopCoroutine().
        {
            if (renderer != null)
            {
                renderer.enabled = !renderer.enabled;
            }
            yield return new WaitForSeconds(interval);
        }
    }

    // A coroutine that executes an action after a delay.
    IEnumerator DelayedAction(float delay, System.Action action)
    {
        yield return new WaitForSeconds(delay);
        action?.Invoke();
    }
}

Notes

Coroutines only run while MonoBehaviour is active. If the GameObject is disabled (SetActive(false)), all its coroutines stop automatically and do not resume when re-enabled. Because coroutines run on the main thread, there are no thread-safety concerns and you can call any Unity API freely.

For long-running async operations such as HTTP requests, C#'s async / await is also available (Unity 2017 and later). Coroutines and async / await can coexist. For Unity math functions, see Mathf; for vector math, see Vector2 / Vector3.

If you find any errors or copyright issues, please .