Coroutines With Unity

As Unity defines, a coroutine is a type of function that is executed in intervals. As we know, Update method is called once every frame. By using coroutines, we can delay the execution of a particular method. In other words, by using coroutines we can pause execution of a method, and continue after the given condition is met.

When you search for coroutines, you will probably encounter the fading example for the coroutines. Imagine that you want to make an object that fades over time. A typical game will run at 60 frames per second as standard. If we don’t use a coroutine, the object might go transparent instantly. Thus, the idea will be to pause the fading of the object for a given amount of time, so that we can perceive the fading by our eyes. You can find the relevant example and a more detailed explanation here.

Coroutines must be created with IEnumerator return type and has to include “yield return” in the body of the method. By using “yield” keyword, we simply tell Unity to “stop here” in this method and continue to run where you left on the next frame. If there is no line after yield return, the coroutine will continue to loop as long as it’s condition is true. Certainly, if you want the method to continue running on the next frame, you can simply type “yield return null”.

To call a coroutine, we use simply StartCoroutine() method, typing the Coroutine’s method in between of the brackets.

Here, you can find an example of coroutines used for delaying spawn of enemies in the space shooter game:

It is crucial to call the coroutines from the correct method. As we know, Update method runs every frame. As I have mentioned, the idea of the coroutines is to cause a delay on a function. Since update function runs every frame, coroutines are usually called from the Start function. Calling a coroutine in Update with a improper constraint might cause your game to crash, making it loop indefinitely.

In this example, we call the method from the start method, after making sure we have successfully cached a reference of player object.

Our condition for the coroutine is to run as long as player is alive. If the player is alive, the method continues to run and instantiates an enemy instance and changes it’s transform parent. When it reaches to yield return line, the method will stop running for 3 seconds. The game will continue to run until the provided time ends, and if the player still has lives left, the coroutine will start again. This loop will continue to run until player object is dead. Alternatively, we can stop a coroutine by force with the StopCoroutine().

Unity Developer