As the title tells I'm trying to make a HTTP Request in Unity (WebGL).
In the documentation I found here: WebGL Networking they tell me to create a IEnumerator
type function and call it via a StartCoroutine
call.
This is all fine, my problem is that I need to provide a callback HttpRequest
to a class that is in another library.
My callback looks like this:
private string HttpRequest(string url, string method, string body=null) {
WWW www = null; // = null is compiler candy
if (method == "GET") {
www = new WWW(url);
} else if (method == "POST") {
//POST specific implementation...
} else {
// do something else
}
while (!www.isDone) { } // this is Wrong.
return www.text;
}
The problem is that unless I return from HttpRequest
and the calling method JavaScript won't be able to handle the request. But on the other hand the calling method expects a string
not some kind of IEnumerator
.
Is there some workaround to let JavaScript do it's work after the WWW class has been constructed?
No
WWW
and UnityWebRequest
are asynchronous.
To do a synchronous request you need write a javascript plugin. By using some library it's not very complicated, such as jquery.
function getdata($url, $method, $data)
{
var text = '';
$.ajax({
url: $url,
type: $method,
async: false, //synchronous request
data: $data,
success: function(data){
text = data;
},
error: function(data){
text = data;
}
});
return text;
}
More information: