What is coroutine.

Suleiman Abdullah
2 min readMay 29, 2024

--

Objective: understand what is coroutine.

A coroutine is the method which can pause execution of code ,then continue execution where it left.

Syntax of coroutine

We start with keyword IEnumerator followed by the name of the method ,doulble parentheses and open and closed curly brackets. Inside the curly bracket we must start with yield return new WaitForSeconds ,then open and close parenthesis inside this you pass amount of seconds. yield mean pause, return new this return a value ,WaitForSeconds is the value as seconds.

IEnumerator EnemySpawnRoutine()
{
return new WaitForSeconds(3f);
}

Note: Inside WaitForSeconds parenthesis’s takes float value so you must end value with f prefix or you will have an error.

Note: A coroutine return more than a seconds ,you can wait for frame by using this attribute yield return null. Or this attribute yield return new WaitForEndOfFrame OR yield return new WaitForFixedUpdate();

How do you call coroutine.

If we call a coroutine like normal method ,it wont do anything.

I create a coroutine and print this every 3 seconds

calling coroutine like normal method

A wright way to call coroutine.

We call call routine inside other method by use StartCoroutine keyword ,the open and close parentheses inside this parentheses we call a coroutine as we called normal method.

This will called after 3 seconds once , since started called once

Best Practice

When we use coroutine ,is best practice to cache the new WaiForSeconds ,if you do so you will increase your app performance or fps. Cause create every seconds cause garbage collection ,garbage collection eat memory due to its behavior but this is advance topic so lets leave it here for now.

See you in the next one

--

--

Suleiman Abdullah

Self taught Unity Developer, who is passion about making games ,and he loves Math For Game Development