How to pass time, using a Coroutine in Unity.

peter arnold
2 min readDec 6, 2022

--

What is a coroutine in unity? Well, it allows you to spread tasks across several frames. In Unity, a coroutine is a method that can pause execution and return control to Unity but continue where it left off on the following frame. Coroutines are still operating on the main thread, they are not multi-thread.

Coroutines can be used for various operations including a time delay, waiting for HTTP transfers, asset loads, fades, ect… I have used coroutines for cool downs, for delayed animation, fading material, and even spawning enemy in games.

How do you call a coroutine you ask, in its own method.

An enemy spawner method using a Coroutine

As you can see the coroutine has a return type of IEnumerator. By using the return type of IEnumerator you are actually creating a kind of save state with the yield return, so if you had a fade using a float you would not lose that info. If you just used a return this would not work as you would only get one go at it, once you hit return it would exit. As in the above I am using WaitForSeconds which will suspend the coroutine execution for a given time using scaled time. There are a few different constructors that can be used like WaitForSecondsRealtime, WaitUntil, and WaitForEndOfFrame just to name a few.

You now have a coroutine but will need to be able to use it. To do this you will need to start the coroutine by using the MonoBehavior Class Member StartCoroutine (method). You will want to use this in a non-repeating way, not alone in update. If you do not control the amount it is called you could find yourself with thousands of coroutines running, crashing your app. Always wrap your coroutine in some kind of conditional statment if you use it in Update().

Coroutine running from Start

Stopping a coroutine is simple, you can destroy the object it is on. You can call the method StopCoroutine. You can also use StopAllCoroutines which will stop all the Coroutines on the script it is called on.

I hope this gives you a little insight into how to use coroutines in Unity.

--

--

peter arnold

I am a passionate, self-motivated game developer with experience in C#, Unity, object-oriented programming, visual studio, java, Python, and C++.