Using Coroutines is a great way of improving the performance of the game. This way we can avoid using Update() by calling the selected method exactly when we want it, and stop it after execution. This way we don’t have to perform check operations in Update() method every frame, what’s slowing down the performance. Even the simplest check performed on multiple objects can slow have significant impact on the game frame rate, especially on mobile devices.
Coroutines are based on IEnumerable interface and Yield Return statement. I encourage you to familiarize yourself with those concepts before moving to this topic.
Waiting Method
It’s common situation in game dev that we want to execute our operation with delay, We can use Invoke() method, but it’s topic for another post. Here is an example of the simplest waiting method
IEnumerator Wait(float sec) { yield return new WaitForSeconds(sec); Debug.Log("Tired of waiting"); }
Once again I encourage you to read the posts about IEnumerable and Yield Return.
Coroutines are executed in main thread. After StartCoroutine() method is called, compiler continues to execute next line of code while the method is working at the same time.
void Start() { StartCoroutine(Wait(2F)); //StartCoroutine("Wait",2f); Debug.Log("Next line executed"); }
There are two ways of calling the method one by it signature, and second by its name as a string, and values after coma. Advantage of second method is that we can stop it with StopCoroutine(“Wait”) function.
In this example we will receive debug log from Start immediately after the start is called. And after 3s we will have debug from Wait function.
Change over time
Another use of coroutines is to perform change over time. We can combine this with Lerp() function to perform linear interpolation. Or we can use it to fade out the renderer.
IEnumerator Fade() { for (float f = 1f; f >= 0; f -= 0.1f) { Color c = renderer.material.color; c.a = f; renderer.material.color = c; yield return null; } }
In this example we place our “yield return null” inside the for loop, this way after each iteration we are coming back to the loop with new values. This have big advantage over Update() method. In next part I’ll cover more complex applications of this concept. Stay Awesome!