Coroutines with Unity

Sherry Fisher
2 min readJul 6, 2023

--

Objective: Use Coroutines to spawn enemies every 5 seconds.

At this point in our game, I have created enemies, but now I need them to continually spawn at regular intervals. To do so, I am going to use a coroutine. A coroutine is going to allow me to pause the code for a short time (5 seconds in this case) so the enemies spawn in intervals rather than continuously.

To accomplish this, I first created an empty object and named it Spawn_Manager.

Creating empty object called Spawn_Manager

Next, I created a C# script called SpawnManager and dragged it onto Spawn_Manager object.

Create a C# script called SpawnManager and drag to Spawn_Manager gameobject.

Then I created the gameobject that I wanted to spawn, the enemy prefab.

Create gameobject that you want to spawn, in this case our enemyPrefab.

I went back to Unity and selected my Spawn_Manager in the hierarchy and dragged my enemy prefab into the Spawn_Manager.

Next, I used an IEnumerator named SpawnRoutine with an infinite while loop to instantiate our enemy prefab every 5 seconds. Normally we would want to avoid infinite loops, but in this case our yield is going to allow a pause that keeps our game from crashing.

Now when I go back to Unity to test my game, enemies begin spawning every 5 seconds.

Prototype game with enemies spawning at top of screen every 5 seconds.

Looking more like a real game every day!

For more information on Coroutines in Unity: https://docs.unity3d.com/Manual/Coroutines.html https://learn.unity.com/tutorial/coroutines#

--

--