Coroutines with Unity!

Dennisse Pagán Dávila
CodeX
Published in
3 min readApr 2, 2021

--

Anyone who has programmed in Unity knows that sooner or later you’ll end up amassing a considerable amount of code in your Update Function. After all, Update is a function called every frame which makes it an extremely helpful tool for programming! However, sometimes we need more precision and customization than Update allows. Sometimes, we need coroutines.

What are coroutines?

A coroutine is a function that is executed in intervals. Simply put, you may tell a function to pause and wait for a condition or action to take place before proceeding. This helps you break down its features into a series of steps that can be carried out sequentially.

A good way to remember their usage is to think of the word routine and what it means in the real world — a sequence of actions regularly followed.

Syntax

The return type of the function will be an IEnumerator, this is how Unity divides the function’s execution across several frames.

Like any regular function, a coroutine can be assigned parameters. Variables will retain their value throughout the coroutine.

Coroutines have a special statement known as yield which returns the execution out of the function. This is what allows you to pause.

Yield is often accompanied by WaitForSeconds which allows you to specify how long to wait.

Return, as a standard feature, terminates execution at that point and transfers control back to the calling process. Yield indicates that the method is an iterator and will execute over more than one frame. When using a coroutine, Unity knows to begin the process where it left off.

A completed coroutine must always be called from the Start method.

Combining a coroutine with a while loop — the right way to make infinite loops

Since coroutines allow the program to breathe you can effectively make a coroutine that will run forever without the program crashing.

However, you can get more specific.

A coroutine can run while a specific condition is in place. This can be exceptionally useful for core game loops such as having enemies spawn while the player is alive.

Code sample:

In this sample, enemies will spawn at random positions within the screen constraints. The _stopSpawning condition is false unless the player dies, or the game is won. This means that this routine will run only while the player is alive or the game is still active, it will not stop otherwise.

What it looks like:

If you are wondering why there is a transform to handle parenting in the object, this is a trick used to declutter the Hierarchy when spawning numerous game objects. I will discuss decluttering in my next article!

--

--

Dennisse Pagán Dávila
CodeX
Writer for

Software Engineer that specialize in Game Development. Currently looking for new opportunities. LinkedIn: https://rb.gy/xdu8nu