Coroutines in Unity3D are functions that allow us to execute game logic over a period of time (or frames) while also being able to add conditions to the execution. For example, if we wanted to instantiate an Enemy Prefab every 5-seconds while the Player is still alive, we would utilize a coroutine.
Let’s take a look at how this is set up.
Step 1: Spawn Manager Setup In Unity
We will create an empty GameObject called Spawn_Manager and a new C# Script called SpawnManager, then attach the script to the Spawn_Manager GameObject.
Step 2: Create Enemy Prefab Variable
Since we want to instantiate an Enemy Prefab, we will need to create a private gameObject variable in the SpawnManager script, called _enemyPrefab, that we can link to the Enemy Prefab in Unity using [SerializeField].
We can save the SpawnManager script, go back into Unity, and drag the Enemy Prefab into the corresponding slot in the SpawnManager (Script) component in the Spawn_Manager GameObject’s Inspector.
Now that the Enemy Prefab is connected to our _enemyPrefab variable, we can instantiate the Enemy Prefab within the SpawnRoutine script.
Step 3: Using IEnumerator
Below the Update() method, we will create a new method, of type IEnumerator, called SpawnRoutine().
Note: IEnumerator is a .NET framework type that can essentially pause iterations, among other tasks, and is used by Unity to carry out coroutines.
For the SpawnRoutine() method to be valid, we need to define the amount of time we would like to pause the code execution by creating a Yield event within the method. For this example, we want the Enemy prefab to spawn every 5-seconds, so our yield event will return that we want to will wait for 5-seconds before spawning a new Enemy Prefab.
Now that the SpawnRoutine() method has been satisfied, we can insert the code to spawn the Enemy Prefab.
Step 4: Instantiate the Enemy Prefab
To instantiate the Enemy Prefab, we will need to execute the code within a while statement.
Note: while statements are endless loops that rely on a yield event to set a pace for the code execution. Without the yield event, the code will execute every frame and can use up all available system memory and crash the system.
Since we already have our yield event, we can build the while statement around it and use True for the condition, meaning it will continuously run the code every 5-seconds. For this example, we will instantiate the Enemy Prefab at 7.5 on the Y-axis and we will use Random.Range to randomize the instantiation between -9.4 and 9.4 on the X-axis.
Step 5: Start the Coroutine
The last step is to start the coroutine within the Start() method.
We can save our script, go back into Unity, and see that the Enemy Prefab now spawns from the top of the screen at random positions every 5-seconds.