A quick guide to coroutines in Unity

Luke Duckett
3 min readApr 5, 2021

In one frame all your code will be called from top to bottom in your update loop. What if you need a pause in the execution but still run everything else?

You could use bools, and “if statements” comparing the current running time to your stored variable times but there is an easier way. They are called coroutines.

What is a coroutine?
A coroutine is a method we can pause execution after a certain period. You determine the time with the call “yield return”. Note that if you do not have a cached variable for your “wait time” you will also need to declare the keyword new when using some of the options below e.g. yield return new WaitForSeconds();”

You do have several options when using this call.

How to create a coroutine?
A coroutine can be private or public and must contain a yield statement. We can declare a method a coroutine by using the keyword “IeNumerator”.

In our example, we will create a simple spawn manager that will instantiate enemies at a random position, with a random spawn time between 3 and 7 seconds.

As you can see, we have all the required components for our coroutine.

How to start and stop a coroutine?

We cannot start a coroutine the same way as we do with a normal function. We have to use the method “StartCoroutine”. Note that how you start a coroutine determines how you can stop it.

We have a couple of options from here. We can directly pass in the coroutine as a string as below.

This method has a couple of distinct disadvantages. The first disadvantage is that when calling a coroutine this way you can only ever provide one parameter in your call. The second disadvantage is that this method is slightly more resource-intensive than our next method.

The most significant advantage to calling a coroutine with strings is that when stopping the coroutine early via code you can stop all instances of that coroutine running.

The other option for starting a coroutine is to pass in the method and initialize it within our “StartCoroutine” call.

The advantage to this method of initialization is that you can assign the coroutine as a variable so you will then open up a lot of options to use on the variable. In our case, we will use the variable to stop our specific instance of our variable, but you can also use the variable to ensure only 1 instance of the coroutine is running at a time or “queue” up more instances to run after this instance finishes (e.g., if you have a speed powerup which lasts 5 seconds and want to add extra time to its duration)

Now we add our script to a “Spawn Manager” game object, we will get our intended effect.

That's all for now.

--

--

Luke Duckett

🎮 First Nations Unity Dev from Wonnarua country 🏞️ | From Player to Lifelong Learner: Crafting Games, Debugging Code, and Embracing New Technology