Using coroutines in Unity

Daniel Kirwan
2 min readApr 1, 2021

--

Have you ever wanted to run a method but you want to delay it for a specific length of time? For me, I want to continuously spawn enemies into my game every 5 seconds so that the player should always have something to shoot at. And to do that I am using a Coroutine. These are special functions that suspend its execution until it is told to execute.

Below you can see the starting code for spawning my enemies and how long the delay is. In these Coroutines you have special instructions that are called ‘yield’ and these allow you to delay the execution. I am using the WaitForSeconds method and using 5 as the length of time. You could also run the Coroutine and pass in a parameter for the length of time if you desire different spawn lengths.

Below is the Coroutine in action and it is spawning enemies into the game scene every 5 seconds.

You can stop a coroutine at any time by calling StopCoroutine but there are some challenges if you started the coroutine using the string method way.

Above you can see that I’m calling the coroutine in two different ways as an example. Calling the method using the string has some performance drawbacks and if you have called the same routine multiple times and want to stop just one, you can’t using the string method as calling StopCoroutine will end all the routines that were called using the string. You can only use a Coroutine with the string if the Coroutine is limited to 0 or 1 parameter.

Using the other way, it is possible to stop a specific Coroutine instance if you have stored a reference when it was started.

It is also possible to stop all coroutines using StopAllCoroutines();

--

--

Daniel Kirwan
Daniel Kirwan

No responses yet