Objective: Explain what coroutines are and why we use them.

Coroutines are simple a way to tell our game or parts of game to wait for a specified time before continuing. This can be particularly in spawning(creating) new game objects such as health packs, power ups or even waves of enemies.

Coroutines use a special type of method called an IEnumerator which is a dotNet collection. They are just used to yield a method from running for a specific time generally in seconds using a return after waiting eg. WaitForSeconds(5). Unlike a regular method where you call it by lets refer back to the game, the Damage method where it was called using Player.Damage(). Coroutines IEnumerator methods are called using the StartCoroutine call.

IEnumerator to log game time

We’ll take a simple example shown in the figure above. The IEnumerator is called WaitAndLogGameTime, pretty easy to understand. It is set to wait 5 seconds before logging how long the game has been running. If you ran the game now nothing would happen as the coroutine hasn’t been called or started.

Starting the coroutine when the game starts

By calling the above code in the figure the coroutine would start when the game starts and every 5 seconds the game would have a new log saying The game is running 5 seconds, with each log adding 5 seconds to the timer.

Coroutines can be called using the string of the coroutine name or by calling like a method, displayed in the figure below.

Calling the coroutine using the method name

Calling using the string variation may be slower to type but it does add the benefit of being able to stop the coroutine. You can only stop a coroutine that was starting by calling it by the string variation of the name. You may not need to stop your coroutine but there will be times when you will want to stop the coroutine such as at the end of an enemy wave or if your coroutine is linked to your player being alive. That way you can have an enemy spawner coroutine only running while your player is alive or has health. We will show an example of this in the next post, where we will create an enemy coroutine.