Coroutines with Unity!

Rob George
2 min readApr 6, 2021

--

Day 9 — Aspiring Game Creator

2D Game Dev: Galaxy Shooter

Implementing the Spawn Manager

Objective: Implement an enemy spawn manager.

In order to spawn enemies, a finite amount or indefinitely, Unity’s coroutine: the IENumerator is the most efficient way to do so.

The IENumerator is special method that allows Unity to play with time. Whereas in a standard method all the code MUST take place within a frame of time, the coroutine allows the method to take place over time by yielding control back to the Update loop for some length of time.

Pseudo Code:

  • Indefinitely spawn an enemy every random X seconds
  • Only spawn enemies while the player is alive

Creating the coroutine is straightforward the return type is ALWAYS: IEnumerator followed by the NAME of the coroutine. In the example of the spawn manager:

In order to let the coroutine wait there’s the YIELD command followed by RETURN. As in any method, return terminates the code! and in this case, temporarily returns execution to Update loop. There are numerous ways to yield, but for the sake of the Spawn Manager, it will yield return for X seconds.

Spawn Manager coroutine

While the player is alive, an enemyPref will be instantiated and then yield control for some length of time: waitTimeBetweenEnemySpawns.

Should the player die while enemies are still spawning, the Player Death sequence makes a call out to the Spawn Manager to stop spawning with:

To kick the coroutine into gear the StartCoroutine command is used:

Including the starting variables

With a handful of variables and basically 5 lines of code the basic Spawn Manager spitting out enemies!

--

--

Rob George
Rob George

No responses yet