0
0
Unityframework~5 mins

Coroutine basics (IEnumerator) in Unity

Choose your learning style9 modes available
Introduction

Coroutines let your program wait or pause without stopping everything. They help do tasks step-by-step over time.

You want to wait a few seconds before doing something, like showing a message.
You want to run a task slowly, like moving an object smoothly across the screen.
You want to load something in the background without freezing the game.
You want to repeat an action every few seconds without blocking other code.
Syntax
Unity
IEnumerator CoroutineName() {
    // code before waiting
    yield return new WaitForSeconds(seconds);
    // code after waiting
}

IEnumerator is a special return type that allows pausing and resuming the function.

yield return tells Unity when to pause and when to continue the coroutine.

Examples
This coroutine waits 2 seconds, then prints a message.
Unity
IEnumerator WaitAndPrint() {
    yield return new WaitForSeconds(2);
    Debug.Log("Hello after 2 seconds");
}
This coroutine prints a message every second forever.
Unity
IEnumerator RepeatMessage() {
    while(true) {
        Debug.Log("Repeating every 1 second");
        yield return new WaitForSeconds(1);
    }
}
Sample Program

This program starts a coroutine when the game begins. It prints a message, waits 3 seconds, then prints another message.

Unity
using UnityEngine;
using System.Collections;

public class CoroutineExample : MonoBehaviour {
    void Start() {
        StartCoroutine(WaitAndPrint());
    }

    IEnumerator WaitAndPrint() {
        Debug.Log("Start waiting...");
        yield return new WaitForSeconds(3);
        Debug.Log("3 seconds passed!");
    }
}
OutputSuccess
Important Notes

Coroutines run alongside other code without freezing the game.

You must start coroutines using StartCoroutine() in Unity.

Coroutines can pause on many things, not just time (like waiting for a condition).

Summary

Coroutines let you pause and resume code smoothly over time.

Use IEnumerator and yield return to create coroutines.

Start coroutines with StartCoroutine() to run them in Unity.