Loading lessons...
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
yieldkeyword. - Return type of coroutines must be
IEnumerator. - Use
UnityWebRequestinside a coroutine to fetch web data. - Enclose web requests in a
usingblock to ensure proper resource cleanup.