Coroutines in Unity

Himanshu Nag
2 min readMay 22, 2021

Introduction

A Coroutine is a function that is capable of waiting and timing its process and pausing it entirely. Coroutines work with a special yield statement that returns the code execution out of the function, then when the functions continue, executions begin again right from where it left off.

Getting Started

Declare Coroutine

Coroutines in C# can be defined by using the IEnumerator keyword followed by the name of the coroutine.

Member variable can be declared by using member-type followed by a variable name.

Coroutine returns type with the yield statement. For example yield return null;

//Defining Coroutine

public IEnumerator MyCoroutine()

{

yield return null;

}

Calling Coroutine

Coroutines can be called using StartCoroutine(Coroutine).

StartCoroutine(MyCoroutine())

Stop Coroutine

Coroutines can be called using StopCoroutine(Coroutine) whereas StopAllCoroutines() can be used to stop all coroutines running at that instance.

//Stop Coroutine

StopCoroutine(MyCoroutine());

//Stop all Coroutine

StartAllCoroutines();

Understanding Coroutines

Coroutines are helpful while developing a game, but using coroutines in a game is not considered efficient if not stopped when the task is completed.

Coroutine methods can be executed piece by piece over time, but all processes are still done by a single main Thread. If a Coroutine attempts to execute a time-consuming operation, the whole application freezes for the time being.

Example Program

using UnityEngine;

using System.Collections;

public class CoroutineHandler : MonoBehaviour

{

public void Start()

{

StartCoroutine(MyCoroutine("Jon"));

}

IEnumerator MyCoroutine(string name)

{

print(name);

yield return new WaitForSeconds(5f);

print(name + "Watson");

}

}

Output

Jon

*waits for 5 sec*

Jon Watson

Conclusion

Coroutines provide a lot of features that can be very helpful while developing games but should be used properly to save memory leaks.

--

--

Himanshu Nag
0 Followers

Senior XR Developer & Analyst @ TCS