Here is the function, I am wondering if there is a more concise way of writing it:
private static WWW WaitUntilResolved (WWW request)
{
bool success = tr
You are really using WWW
and isDone wrong. If you must use isDone
, you must put it in while loop. You must also yield in the while loop with yield return null;
otherwise the game will freeze until the download is done. This whole thing requires coroutine so the function must be made a coroutine function.
You really don't need isDone
. That's only used when you want to know the progress of the download.
Here is a proper way to use isDone
:
private static IEnumerator WaitUntilResolved(WWW request)
{
while (!request.isDone)
{
Debug.Log("Download Stat: " + request.progress);
//Wait each frame in each loop OR Unity would freeze
yield return null;
}
if (string.IsNullOrEmpty(request.error))
{
//Success
}
}
If you don't need to know the progress of the download then below is something you should use:
private static IEnumerator WaitUntilResolved(WWW request)
{
yield return request;
if (string.IsNullOrEmpty(request.error))
{
//Success
}
}
Finally, you cannot call a coroutine function directly. You have to use StartCoroutine function to do that:
WWW www = new WWW("www.yahoo.com");
StartCoroutine(WaitUntilResolved(www));
EDIT:
How do I set a timeout for the coroutine?
Most WebRequest
tutorials uses timer. You don't need to do that in Unity with the WWW
API. It is not necessary here because this is a non blocking operation. If you must then see the code below.
private static IEnumerator WaitUntilResolved(WWW request)
{
float timeout = 5000, timer = 0;
while (!request.isDone)
{
Debug.Log("Download Stat: " + request.progress);
timer += Time.deltaTime;
if (timer >= timeout)
{
Debug.Log("Timeout happened");
//Break out of the loop
yield break;
}
//Wait each frame in each loop OR Unity would freeze
yield return null;
}
if (string.IsNullOrEmpty(request.error))
{
//Success
}
}
If you need to return the status of the download, see this post that explains how to do that.
Here is an example of waiting for async call.
string WebGet()
{
Response result = new Response();
IEnumerator e = GetStuff(result);
// blocks here until UnityWebRequest() completes
while (e.MoveNext());
Debug.Log(result.result);
}
public class Response
{
public string result = "";
}
IEnumerator GetStuff(Response res)
{
UnityWebRequest www = UnityWebRequest.Get("http://some.add.com/");
yield return www.SendWebRequest();
while (!www.isDone)
yield return true;
if (www.isNetworkError || www.isHttpError)
res.result = www.error;
else
res.result = www.downloadHandler.text;
}