How to use coroutines in Unity?
A coroutine is a function that has the ability to pause execution and return control to Unity but then to continue where it left off on the following frame.
A coroutine is declared with a return type of IEnumerator and with the yield return statement included somewhere in the body.
Using a coroutine you can get an update regularly but not every single frame like in the MonoBehaviour “Update()” function.
So with coroutines you can:
- Make things happen step by step;
- Write functions that need to happen over time;
- Write functions that have to wait for another operation (function) to complete.
Hera is a C# example of a coroutine that fades a gameObject (changes its transparency slowly):
IEnumerator Fade()
{ //The transparency of a gameObject is controlled by the alpha value
//of its color (rgba = red, green, blue, alpha) which is between 0 and 1for (float alphaValue = 1f; alphaValue >= 0; alphaValue -= 0.1f)
{
// Get the color of the current gameObject.
Color c = renderer.material.color;
// Assign the current value of alphaValue to the alpha property of color c.
c.a = alphaValue;
// Assign the color c to the gameObject color.
renderer.material.color = c;
// Execution will pause and be resumed the following frame
yield return null;
}
}
To set a coroutine running, you need to use the “StartCoroutine” function:
Void Update()
{
if (Input.GetKeyDown("f")) //If the f key is pressed
{
StartCoroutine("Fade");
}
}
It is also possible to introduce a time delay using “WaitForSeconds”:
IEnumerator Fade()
{
for (float alphaValue = 1f; alphaValue >= 0; alphaValue -= 0.1f)
{
Color c = renderer.material.color;
c.a = alphaValue;
renderer.material.color = c;
//Wait for 0.1 second before continuing the execution
yield return new WaitForSeconds(.1f);
}
}
Here’s what you can yield (YieldInstruction) :
Note that coroutines are not stopped when a MonoBehaviour is disabled, but only when it is definitely destroyed. You can stop a Coroutine using the MonoBehaviour “StopCoroutine” method and the MonoBehaviour “StopAllCoroutines” method. Coroutines are also stopped when the MonoBehaviour is destroyed or when the GameObject it is attached to is disabled.
“Yield return new WaitForSeconds” is dependent on game time which is affected by “Time.timeScale”.