How to use coroutines in Unity Engine
Check-out the original post here.
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:
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.
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.