CodeBlanks Logo Icon CodeBlanks

StartCoroutine

Learn to start a coroutine with StartCoroutine.

Launching with StartCoroutine

Coroutine methods cannot be invoked like regular functions by simply writing SpawnWave(). They must be registered into Unity's execution loop through the StartCoroutine() method on a MonoBehaviour.

void Start() {
    // Launching the coroutine
    StartCoroutine(SpawnEnemyWave());
}

When StartCoroutine is called, execution runs immediately up to the first yield statement, where pausing begins.

Storing a Coroutine reference

The StartCoroutine method returns a Coroutine handle object. Storing this reference in a variable is vital for identifying and halting that specific routine later.

Coroutine activeRoutine;

void FireSkill() {
    activeRoutine = StartCoroutine(CastSpell());
}

Without caching this reference, targeting and terminating one specific routine among multiple concurrent instances is difficult.

Practice Print launcher and target method

Assign "StartCoroutine" to launcher and "SpawnWave" to targetRoutine. Print Launcher: StartCoroutine | Routine: SpawnWave to the console.

Starter code

Player.cs
using System;

class Program
{
    static void Main()
    {
        // launcher ve targetRoutine değerlerini tanımlayıp yazdır
    }
}

Sample solution

Player.cs
using System;

class Program
{
    static void Main()
    {
        string launcher = "StartCoroutine";
        string targetRoutine = "SpawnWave";
        Console.WriteLine("Launcher: " + launcher + " | Routine: " + targetRoutine);
    }
}

Expected output

Launcher: StartCoroutine | Routine: SpawnWave

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is the correct way to run an 'AttackRoutine' coroutine returning IEnumerator in a MonoBehaviour script?

  • StartCoroutine(AttackRoutine()); Correct answer
  • AttackRoutine();
  • run AttackRoutine();
  • new AttackRoutine();

Explanation: Coroutines do not execute when called directly; they must be launched through the StartCoroutine wrapper.

2 Start coroutine and cache reference

Question
Coroutine routine = ____(DoSomething());
Answer
Coroutine routine = StartCoroutine(DoSomething());

Explanation: The StartCoroutine method is invoked to launch a coroutine in Unity.

3 Launch concepts

Term Meaning
StartCoroutine Method to start coroutine
Coroutine Running coroutine handle
MonoBehaviour Class with StartCoroutine
Metot Çağrısı Function passed to StartCoroutine

All lessons in Intermediate