- Home /
WWW, RESTful Service, and Threading
I have a basic unity scene that should instantiate game objects based on the result of a simple GET of a RESTful web service. I have a very simple example of calling this web service here from unity:
using UnityEngine;
using System.Collections;
public class Updater : MonoBehaviour {
void Start () {
string url = "http://MyRestfulServiceUrl/Service1.svc/someGetMethod?id=1";
WWW www = new WWW(url);
StartCoroutine(WaitForRequest(www));
}
IEnumerator WaitForRequest(WWW www)
{
yield return www;
// check for errors
if (www.error == null)
{
Debug.Log("WWW Ok!: " + www.data);
} else {
Debug.Log("WWW Error: "+ www.error);
}
}
}
The result of the web service may take a second or 2 to respond. Additionally the response data may be a blob of XML that needs to be parsed - However I do not want these operations to effect the main UI thread. Is using threads to create a background 'call web service and parse response' thread an appropriate solution? Are there better/alternate solution to consider?
PS I am not too familiar with coroutines but my understand is that they are not really asynchronous background threads?
Answer by whydoidoit · Jul 28, 2012 at 04:22 PM
Coroutines are not threads, they are just routines that execute partially on the main thread and then continue from where they left off later.
You can't use the Unity API from a second thread, but you can certainly process data. I use threads to run ZXing and detect qr codes which works quite well.
You might use a coroutine to wait for the WWW then run a thread to process the returned data.
So it sounds like I should be able to do the processing of X$$anonymous$$L in a separate thread. The result of the X$$anonymous$$L will update some object values in the scene and then the main unity thread should be able to respond accordingly.
Yeah, you'll just need to send the data back to the main thread.
On. this post you can see how I use my Loom class to handle this stuff, the class itself is included in the download.
Your answer
Follow this Question
Related Questions
WWW class implemented with threads? 1 Answer
i think www blocks display thread 1 Answer
Using a method to get the string from a download. 3 Answers
How do I use RESTful apis from Unity? 0 Answers