How to use coroutines in Unity Engine

How To Tech
2 min readJul 26, 2021

Check-out the original post here.

unity 3d logo

Coroutines are method capables to run independently of the main thread. This gives them great capability to manage the flow of the project; like easy looping and conditional behaviors.

Those Coroutines are also very useful in cases of big projects: allowing a smooth execution of tasks, that otherwise would have stopped it.

Coroutines need an IEnumerator, but let’s dive in to better understand how to use them.

As the manual teach us:

void Update()
{
if (Input.GetKeyDown("f"))
{
StartCoroutine("Fade");
}
}

Here’s above, we set in the update method that, every time we press the “f” key, we’ll call, with the StartCoroutine function, the “Fade” coroutine.

IEnumerator Fade()
{
for (float ft = 1f; ft >= 0; ft -= 0.1f)
{
Color c = renderer.material.color;
c.a = ft;
renderer.material.color = c;
yield return new WaitForSeconds(.1f);
}
}

The coroutine up here, will change the object’s alpha color untill it’ll be invisible. Without the need of being placed in the Update function. Like pausing the process, fading the object, and then continuing where the task was left.

This is just an example of the coroutines possibilities, the argument is pretty wide so if you like to learn more on it, you can check Unity learn to have a solid start.

--

--

How To Tech

Quick tutorials on Photoshop, Unity 3D, Facebook, WhatsApp, Windows and some Game news