Journal 12 — Practice Coroutines in Unity

Chris Nielsen
2 min readApr 28, 2021

I first mentioned coroutines in my Journal 07 article on creating enemies. Coroutines in Unity and C# can be used for creating actions that need a specific timing, a series of steps, a series of music or visual effects, or running something that would take longer than a single frame.

Coroutines consist of a call to an IEnumerator function using the StartCoroutine command.

Coroutines in this example are used for spawning enemies at a regular interval. We add the StartCoroutine command in the Start Method, and use the Instantiate command plus a period of time to wait per each spawn in the IEnumerator function.

Unity C# Coroutine command in void Start
Unity C# IEnumerator to control spawn rate

Without a coroutine, if you spawned enemies in the Update Method, this is what would happen:

Unity Playmode — spawn enemies in Update (whoops!!)

Here’s the result with a coroutine:

Unity Playmode — spawn enemies at regular 5-second interval

Here’s another variation of the same coroutine with a random waiting period for spawning: yield return new WaitForSeconds(Random.Range(2f,5f)); This makes the enemy spawning a little more unpredictable as the game gets fleshed out.

Unity Playmode — spawn enemies at random 2–5 seconds interval

I appreciate your time stopping by.

Thanks!

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

Chris Nielsen
Chris Nielsen

Written by Chris Nielsen

An Engineering Manager consultant who is seeking additional skills using Unity 3D for game and application development.

No responses yet

Write a response