没有 IEnumerator 或协程的 Unity WebGL HTTP 请求

Unity WebGL HTTP Request without IEnumerator or Coroutine

如标题所示,我正在尝试在 Unity (WebGL) 中发出 HTTP 请求。

在我在这里找到的文档中:WebGL Networking 他们告诉我创建一个 IEnumerator 类型的函数并通过 StartCoroutine 调用来调用它。

一切都很好,我的问题是我需要向另一个库中的 class 提供回调 HttpRequest

我的回调是这样的:

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;
}

问题是,除非我从 HttpRequest return 和调用方法 JavaScript 将无法处理请求。但另一方面,调用方法期望 string 而不是某种 IEnumerator.

在构建 WWW class 之后,是否有一些解决方法可以让 JavaScript 正常工作?

没有

WWWUnityWebRequest 是异步的。

要执行同步请求,您需要编写一个 javascript 插件。通过使用一些库,它不是很复杂,例如 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;
}

更多信息:

Communication between javascript and unity

jquery.ajax