Coroutines

Scripting a checklist for your objects

A coroutine is a function that is gives an object a set amount of actions to complete set within a schedule like manner. An example would be setting up an spawn manager and having enemies spawn after a set amount of time.

How to apply coroutines

There are many ways to apply coroutines into your scripts and can be used effectively due to its optimization. Making a spawn manager for spawning enemies, we would need an type of coroutine called “IEnumerator”. With “IEnumerator”, it allows the coroutine to “yield” its function and “wait” a set amount of seconds before restarting the coroutine.

An Spawn Routine with an 5 second wait.

In this example, we have placed everything within a “While Loop” since we want to have the enemies infinity spawn, but be cautious since while loops are infinite and take up quiet a bit of compute memory. If not handle properly, it will cause the program to crash.

In the while loop, we will instantiate the enemy prefabs at random values on the scene. The “Yield return” function allows us to pause the coroutine to a set specification. In this example, we use “Wait for Seconds” therefore after a set amount of seconds has passed, the coroutine would pick up function again.

How to Start a Coroutine

There are two ways to start an coroutine, either through a string or through and optimized way by invoking the method name itself.In the void start section type in “StartCoroutine(**name given to the IEnumerator**)”.

Starting a Coroutine

A Designer, an Illustrator and a massive tech geek aspiring to become a professional Unity Developer.

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

Recommended from Medium

5 Principles to write SOLID Code (examples in Python)

TODO: Make TODO Comments Better For Everyone

How to Kubernetes: Use Conftest to Audit Infrastructure-As-Code

GitHub Codespaces, Visual Studio Code and Remote Containers

GitHub Codespaces, Visual Studio Code and Remote Containers

How We Gaymoji: An Exercise in XP

Accessing the Dark Web with Python

Difference Between Class and Object in c++

DAG Algorithm

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
Simon Truong

Simon Truong

A Designer, an Illustrator and a massive tech geek aspiring to become a professional Unity Developer.

More from Medium

Fortinet NSE 4 — FortiOS 7.0 NSE4_FGT-7.0 Questions and Answers

WHAT IS SHANTI?

My friend said I should not use languages like Java or C# to learn data structures and algorithms…

New Project Announcement: Strings Theory