Coroutines in Unity

Stephen York
2 min readMar 23, 2021

Spawning in Update()

When it comes to spawning enemies in game, coroutines are life savers. Coroutines allow you to define a wait period before code executes.

To create a coroutine, you simply create an IEnumerator which require a yield, or delay. For example, creating coroutine to handle spawning enemies for a 2D space shooter game.

To start, create the IEnumerator and name it something relevant, like SpawnRoutine. Then since we want enemies to continuously spawn for the life of the game, we create a while loop with a bool condition so we can stop it if the player dies. Inside the while loop we create the enemy, the example below is with object pooling. Then it’s just setting the position of the enemy we create. Then we get the

This sets the delay before the script continues its execution. Yield return sets up the following as a wait period, and the new WaitForSeconds(Random.Range(1f, 5f)) sets the delay to be a random float value between the values of 1 and 5.

With the coroutine created, it is simply called with StartCoroutine() with the name of your coroutine:

Now one enemy will be created after a delay of 1–5 seconds and that completes the creation of coroutines.

Coroutine with wait time of 1 to 5 seconds

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Stephen York
Stephen York

Written by Stephen York

An Atlanta based Unity developer, who enjoys running, reading, and creating videogames!

No responses yet

Write a response