Unity/C# Challenge 9: Coroutines with Unity

Alec Oney
1 min readJun 29, 2021

Challenge: Create an enemy spawn manager in Unity.

Right now, we have a single enemy in our game that was created directly. What we want is a program within our game that automatically creates enemies when certain conditions are met. To do this, we first create an empty game object (called SpawnManager) and attach a new script to it. For our purposes, we want enemies to spawn every five seconds:

coroutines use the “Yield” function to decide when to run their assigned code

Here, we are creating the coroutine called SpawnRoutine, which, will wait two seconds (yield return new WaitForSeconds(2f);); before creating an enemy at the top of the screen and along a random point on the x-axis (Instantiate(Enemy, bounds, Quaternion.identity);). For demonstration, an int a was created , with the coroutine only running when “a” is greater than 0. Since every time the code runs, 1 is subtracted from “a”; this caps the amount of enemies the SpawnManager produces:

To finish, place

StartCoroutine(SpawnRoutine());

in your start method.

--

--