Coroutines in Unity: Part 3 – Usage

Coroutines in Unity: Part 3 – Usage

In the previous parts, we learned the basics of Coroutines in Unity and some interesting facts about them. In this part, we will learn when we can use coroutines in Unity.

Downloading data from the server

When you are downloading data from internet, let say hitting the server for a GET or POST request, coroutines are used. Here are some examples:

GET Request
   public IEnumerator CallGetApi(string serverUrl)
    {
        using (UnityWebRequest webRequest = UnityWebRequest.Get(serverUrl))
        {
            // Request and wait for the desired page.
            yield return webRequest.SendWebRequest();
            if (!webRequest.isNetworkError)
            {
                Debug.Log(webRequest.downloadHandler.text);
            }
        }
    }
POST Request
    string serverUrl;
    string formKey;
    string formValue;
    public IEnumerator CallPostApi()
    {
        WWWForm wForm = new WWWForm();
        wForm.AddField(formKey, formValue);
        using (UnityWebRequest www = UnityWebRequest.Post(serverUrl, wForm))
        {
            yield return www.SendWebRequest();
            if (www.isNetworkError || www.isHttpError)
            {
                Debug.Log(www.error);
            }
            else
            {
                Debug.Log(www.downloadHandler.text);
            }
        }
    }

Usage of Coroutines in Unity over update

We mostly use the Update function to perform periodic tasks. However, this function is called many times per second. You can use a coroutine when you do not need periodic task to repeat every frame. The example can be seen here.

Execute a task after an event occurs

If we want to run a task after an event occurs, we can make use of coroutines using WaitUntil() CustomYieldInstruction. WaitUntil suspends the coroutine execution until the supplied delegate evaluates to true. Lets say I want to wait till timer > 0, and show the game over screen as soon as timer< 0, we will use:

   IEnumerator WaitForTimer(){
        yield return new WaitUntil(()=> timer < 0);
        Debug.Log("Show Game Over screen");
    }

The condition inside WaitUntil should be a bool condition. The coroutine waits till this condition is false and as soon as this condition returns true, the coroutine completes its execution.

Coroutines in Unity can be used to spread an effect over a period of time

Lets say you want to show a fading effect. If you put the loop in Update, you will not be able to see the transition. However, coroutines are helpful in these cases.

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(0.1f);
    }
}

This concludes the Coroutines tutorial.

Happy Coding!

Share This Post

Post Comment