【问题标题】:Unity WWW Post failure in WebGLWebGL中的Unity WWW Post失败
【发布时间】:2017-07-13 02:53:33
【问题描述】:

我有一个在 WebGL 中运行时失败的类,但它在 UNITY IDE(5.6.1f1 个人(加)版)中工作。代码在下面“修剪”,但产生相同的特征(作为 WebGL 失败并且在 UNITY IDE 中运行没有问题。)我将它指向一个服务 URL 并在测试时得到正确的响应,但是从 WebGL 运行时 Post 实际上永远不会发生,并且在没有响应时会崩溃(甚至没有收到错误)。我想从社区获得想法(也许我需要设置特定的构建参数或修改代码实现?)非常感谢有用的反馈。谢谢。

-------------------- 包装器和 JSON 实用程序类 ----------------

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class JsonTest : MonoBehaviour {

    JsonCommunicationManager jsonComm;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

    }

    public void OnMouseDown()
    {

        var jsonCommunications = gameObject.AddComponent<JsonCommunicationManager>();
        string tempReturn = jsonCommunications.PostStartUpRequest("{\"userId\":1,\"id\":1}");
        Debug.Log("JSON RequestStartParms: Response :  " + tempReturn);

    }
}


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class JsonCommunicationManager : MonoBehaviour
{

    private WWW wwwForm;


    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }

    public string PostStartUpRequest(string JsonPostMessage)
    {

        Debug.Log("Inside PostMessage:");

        string JsonReturnMessage;

        StartCoroutine(PostWWWMessage(JsonPostMessage));

        bool boolResponse = false;

        do
        {
            Debug.Log("Checking for Response ");
            try
            {
                JsonReturnMessage = wwwForm.text;
                boolResponse = true;
            }
            catch
            {
                WaitForResponse();
                Debug.Log("Inside JsonPost Message:  WAIT");
            }
        } while (!boolResponse);

        JsonReturnMessage = wwwForm.text;

        Debug.Log("Inside JsonPost Message: Messgae Response Received: ");
        Debug.Log("Inside JsonPost Message: Messgae Response Data: " + JsonReturnMessage);
        Debug.Log("Inside JsonPost Message: Messgae Response Received: ");
        Debug.Log("Inside JsonPost Message: Messgae Response Error: " + wwwForm.error);
        Debug.Log("Inside JsonPost Message: Messgae Response Received: ");

        return JsonReturnMessage;
    }

    //private void PostWWWMessage(string JsonPostMessage) {
    private IEnumerator PostWWWMessage(string JsonPostMessage)
    {

        Debug.Log("Inside PostWWWMessage:");
        Dictionary<string, string> headers = new Dictionary<string, string>();
        headers.Add("Content-Type", "application/json");
        byte[] postData = System.Text.Encoding.ASCII.GetBytes(JsonPostMessage.ToCharArray());
        string fullyQualifiedURL = "https://jsonplaceholder.typicode.com/posts";

        Debug.Log("Inside PostWWWMessage: Posting Message: " + JsonPostMessage);
        print("Posting start up request to: " + fullyQualifiedURL);
        print("Post Data is:                " + postData);
        print("Post Header is:              " + headers);
        wwwForm = new WWW(fullyQualifiedURL, postData, headers);

        WaitForResponse();

        yield return null;

    }

    private IEnumerator WaitForResponse()
    {
        yield return new WaitForSeconds(1);
    }



}

【问题讨论】:

  • 试过调试了吗?

标签: c# json unity3d unity-webgl


【解决方案1】:

当你试图在不了解协程的情况下构建一个完整的程序时会发生这种情况。我鼓励你创建一个新项目,找到一个协程教程并研究它是如何工作的。我觉得这是你理解协程最好的方式。

你的代码有问题:

1.尝试在带有协程的 void 函数中等待。这是您在 PostStartUpRequest 函数中调用 WaitForResponse() 的地方。这将不会等待,因为 PostStartUpRequest 是一个 void 函数。将PostStartUpRequest 设为IEnumerator 函数,然后等待yield return WaitForResponse();

2。在 void 函数中有一个 while 循环,该循环等待另一个变量状态在另一个函数中发生变化。 while (!boolResponse); 不是一个好主意,除非你是从另一个线程做的,但你不是。这将冻结 Unity,因为您没有给其他功能运行机会。您可以通过在每次检查后等待帧的 while 循环中添加 yield return null; 来解决此问题。这允许其他功能运行。您必须将 PostStartUpRequest 函数更改为 IEnumerator 函数才能执行此操作。

do
{
    //Wait for a frame
    yield return null;
    ....
} while (!boolResponse);

你遇到的崩溃很可能来自这里。

3。当您从 PostWWWMessage 函数调用 WaitForResponse(); 函数以等待 1 秒时,这应该不起作用,因为您是 屈服。您必须等待WaitForResponse() 函数完成等待。你可以通过 yield it 来做到这一点。

应该是yield return WaitForResponse(); 而不是WaitForResponse()

4.未正确等待WWW 请求完成。 Webrequest 取决于设备和互联网的速度。有时,它可能需要超过您等待的一秒钟。您必须产生 WWW 请求,而不是等待 1 秒。

//Make request
wwwForm = new WWW(fullyQualifiedURL, postData, headers);
//Wait for request to finish
yield return wwwForm;

//Now you can safely use it:
JsonReturnMessage = wwwForm.text;

5.在访问网络请求结果之前不检查错误。

您需要在访问结果之前检查可能的错误,否则会发生任何事情,例如从服务器接收null 值。

if (String.IsNullOrEmpty(wwwForm.error))
{
   //No Error. Access result
    JsonReturnMessage = wwwForm.text;
}else{
   //Error while making a request
   Debug.Log(wwwForm.error);
}

最后,我不知道为什么你对一个简单的网络请求有这么多的功能。只需使用一个函数即可。

private WWW wwwForm;

// Use this for initialization
void Start()
{
    StartCoroutine(PostWWWMessage("Test"));
}

//private void PostWWWMessage(string JsonPostMessage) {
public IEnumerator PostWWWMessage(string JsonPostMessage)
{

    Debug.Log("Inside PostWWWMessage:");
    Dictionary<string, string> headers = new Dictionary<string, string>();
    headers.Add("Content-Type", "application/json");
    byte[] postData = System.Text.Encoding.ASCII.GetBytes(JsonPostMessage.ToCharArray());
    string fullyQualifiedURL = "https://jsonplaceholder.typicode.com/posts";

    Debug.Log("Inside PostWWWMessage: Posting Message: " + JsonPostMessage);
    print("Posting start up request to: " + fullyQualifiedURL);
    print("Post Data is:                " + postData);
    print("Post Header is:              " + headers);
    wwwForm = new WWW(fullyQualifiedURL, postData, headers);
    //Wait for the request
    yield return wwwForm;

    string JsonReturnMessage;
    //Check for error
    if (String.IsNullOrEmpty(wwwForm.error))
    {
        //No Error. Access result
        JsonReturnMessage = wwwForm.text;
        Debug.Log("Received: " + JsonReturnMessage);
    }
    else
    {
        //Error while making a request
        Debug.Log(wwwForm.error);
    }
}

【讨论】:

    猜你喜欢
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 2017-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-21
    • 1970-01-01
    相关资源
    最近更新 更多