Hi, I am using Coroutines to perform web requests and take things from my asset folder. I would like to know how can I have the info taken from the web request (which are strings or also images) out of my coroutine? Because then I need to have these data inside my start () method and go ahead with the other instructions. I’ve heard about callbacks but have no clue how to do it.
I am really in a hurry since I have a strict deadline to end the project for university.
Thanks a lot
FIrst of all, Callbacks. Unity runs in what is often called the Game Loop (Input – Update – Render) and offers various hooks in the loop. For example. Unity says: “I’m about to update the frame. Anything you want to do first?” or “I’m about to do all my physics calculations. Anything you want to throw into the mix?”. These are examples of callbacks and are better known by their common names: Update()
and FixedUpdate()
. Do they play a part in Coroutines? Not really.
The thing about Coroutines is that they don’t have a return type so, at first glance, don’t return any values (unlike Async which can). However, it’s easy enough to get data back. A common way is to pass a generic List. Here’s an example:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CoroutineTest : MonoBehaviour
{
void Start()
{
List<string> myList = new List<string>();
myList.Add("qwerty");
StartCoroutine(Coro(myList));
print(myList[0] + " " + myList[1]);
}
IEnumerator Coro(List<string> myList)
{
myList[0] = "Tom";
myList.Add("And Jerry");
yield return null;
}
}
This is useful if you’re returning strings from a web page. You can also pass a second List, this time of textures. See the sample code on UnityWebRequestTexture.GetTexture if you already haven’t got a handle on this.