How To Use IEnumerator Coroutines In Unity!

A standard “void” method applies its functions all within a single frame. Coroutines allow the use of the “yield” function to suspend the method until either the next frame or a set amount of time goes by.

[IMPORTANT NOTE]

When using a coroutine you must make sure that you are using the “using System.Collections;” namespace.

This is an example of an “IEnumerator” coroutine utilizing a while loop with “yield return new WaitForSeconds()” embedded in it to spawn new enemies at a random location on the top of the screen every second.

This is an example of a “void” method that spawns new enemies at a random location on the top of the screen.

Notice that it’s spawning a ton of enemies all at once. If I had left it in the while loop instead of moving it into the void Update function, it would have crashed Unity and possibly my computer.

Here’s how to use the IEnumerator function to create coroutines!

By using “yield return null;” in your coroutine, you end the method until the next frame.

By using “yield return new WaitForSeconds(x);” in your coroutine, you can input a float value to set a specific number of seconds that you want the method to wait before continuing.

[IMPORTANT NOTE!]

IEnmumerators require at least 1 “yield” event in order to work!

[EXTRA]

You can put the WaitForSeconds function in between two different statements!

Hi, my name is Adam Reed and I am a software engineer specializing in Unity and C# development. Feel free to scroll through and check out some of my work!

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

The entire team is very excited to announce the new Stablecomp updates!

Best practices and tips for writing unit tests for Django applications

Don’t ever again write // TODOs

Weak Key Exchange (KEX) Algorithm(s) Supported (SSH)

Mobile features for your website

Using Codemagic CI/CD for React Native apps

Learning Python With Program Templates: Prompt, Then Read

Quantum programming introduction with Qiskit

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Adam Reed

Adam Reed

Hi, my name is Adam Reed and I am a software engineer specializing in Unity and C# development. Feel free to scroll through and check out some of my work!

More from Medium

What’s new in PVS-Studio in 2021?

Mastering Unity Scripting | Summary — Chapter 1: Unity C# Refresher

MVC Pattern in Unity — Less Code Dependency and Better Code Architecture