StartCoroutine
- Game Development course
- Intermediate
- Lesson 46/83
- 4 min
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
using System;
class Program
{
static void Main()
{
// launcher ve targetRoutine değerlerini tanımlayıp yazdır
}
}Sample solution
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
Coroutine routine = ____(DoSomething());
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 |