Lesson 21 +10 XP

Coroutines & Web Requests

Coroutines & Web Requests

Standard methods execute completely within a single frame. To manage timed behaviors or fetch data from remote servers, Unity provides Coroutines and the UnityWebRequest API.

Coroutines

A Coroutine is a function that can suspend execution (yield) and resume in subsequent frames:

  • Declare return type as IEnumerator.
  • Start using StartCoroutine(MyCoroutine()).
  • Yield Instructions:
  • yield return null;: Suspends execution until the next frame.
  • yield return new WaitForSeconds(2.0f);: Suspends execution for a specific duration.
IEnumerator SpawnWaves()
{
    yield return new WaitForSeconds(1.0f);
    Debug.Log("Wave 1 Spawning!");
}

Interacting with Web Servers

To send HTTP requests, import the UnityEngine.Networking namespace and use UnityWebRequest:

IEnumerator GetServerData()
{
    using (UnityWebRequest webRequest = UnityWebRequest.Get("https://api.example.com/data"))
    {
        yield return webRequest.SendWebRequest();
        if (webRequest.result == UnityWebRequest.Result.Success)
        {
            Debug.Log("Received: " + webRequest.downloadHandler.text);
        }
    }
}

TL;DR

  • Coroutines pause execution using the yield keyword.
  • Return type of coroutines must be IEnumerator.
  • Use UnityWebRequest inside a coroutine to fetch web data.
  • Enclose web requests in a using block to ensure proper resource cleanup.