Be Back In Five With Coroutines

Eric Philippot
2 min readJul 4, 2022

--

Coroutines are methods that can pause code execution for a given amount of time. In Unity, coroutines are great for delaying or spreading a task over multiple frames. In one case of spreading tasks over multiple frames, is creating an infinite loop to spawn enemies or obstacles into the game.

In one of my previous posts, I used a coroutine to create a cool down effect.

Script on player game object for shooting logic and cool down functionality

To create the coroutine, I called IEnumerator and named it “CoolDownTimer”. I supplied it with the yield return keywords and told it to wait for a cool down period of 10 seconds after the player spammed the fire button over a short period of time. To start the coroutine, I had to use the StartCoroutine() method and pass it the name of the IEnumerator.

Another way I used a coroutine, was spawning the enemies.

Game play of enemies spawning in random loactions.
Script illistrating the spawning logic of the spawn manager script.

The logic to this was to grab a reference to the enemy prefab by creating an option to drag the prefab of reference, into the SpawnManager script component. Create a coroutine to run spawning logic every 2 to 6 seconds while the game was not over and making sure there was an enemy prefab. Otherwise the loop is skipped. I probably should have placed a StopCoroutine method in there if the loop was skipped…. Next time. 😅

I also added a way to organize the inspector tab from instantiated game objects.

Here I created a reference to the spawned enemy and stated that its parent is an empty game object named Enemy Container. This will organize all the enemies, making it easier to debug sort through issues in the inspector.

--

--

Eric Philippot

Game and Web Developer with a joined experience of 6 years.