簡體   English   中英

C#Unity3D JSON掛起

[英]C# Unity3D JSON Hanging

首先,我必須指出,我是C#的新手。 我正在使用Unity3D開發應用程序,並且該應用程序的一部分要求我解析存儲在服務器上的JSON文件。

我遇到的問題是,有時一切正常,而其他時候應用程序在下載JSON時掛起。 我沒有收到任何錯誤,腳本永遠不會達到進度的100%。

這是我的代碼:

public IEnumerator DownloadJSONFile(string url) 
{
        Debug.Log("JSON URL: "+ url);
        mJsonInfo = new WWW(url);
        yield return mJsonInfo;

        mIsJSONRequested = true;
 }
private void LoadJSONData(string jsonUrl)
{

    Debug.LogWarning("LoadJSONData, url= "+jsonUrl);

    if(!mIsJSONRequested){

        StartCoroutine(DownloadJSONFile(jsonUrl));

    } else {

        if(mJsonInfo.progress >= 1)
        {


            if(mJsonInfo.error == null )
            {

                //** PARSE THE JSON HERE **//

            }else
            {
                Debug.LogError("Error downloading JSON");
                mIsLoadingData = false;
            }


        } else {
            Debug.LogWarning("!! ### JSON DOWNLOADING: "+mJsonInfo.progress+"%");
            if(mJsonInfo.error != null )
                {
                    Debug.LogError("Error downloading JSON");
                    Debug.LogError("JSON Error:"+mJsonInfo.error);
                    mIsLoadingData   = false;
                }
        }
    }
}

就像我說的那樣,JSON數據幾乎有50%的時間幾乎立即被加載,進度從未達到1的時間有50%。我從來沒有收到mJsonInfo.error變量形式的錯誤。

關於我在做什么錯的任何建議,將不勝感激!

您需要等待下載完成。

文檔中所述,您需要:

var www = new WWW(...);
yield return www;

因此,您需要將方法的返回類型從void修改為IEnumerator

private IEnumerator LoadJSONData(string jsonUrl)
{
    Debug.LogWarning("LoadJSONData, url= "+jsonUrl);

    if(!mIsJSONRequested)
    {
        // Gets the json book info from the url
        mJsonInfo = new WWW(jsonUrl);
        yield return mJsonInfo; //Wait for download to complete
        mIsJSONRequested = true;
    } 
    else 
    {
      ...
    }
}

isDone是您需要的,

WWW lWWW = new WWW(...)
if(lWWW.isDone)
 then parse it

我找到了問題,我想我應該將解決方案發布給其他遇到相同問題的人。 最后的解決方案是服務器上的JSON文件。 我使用PHP(CakePHP)生成JSON,通過瀏覽器打開PHP生成的文件時,響應時間是即時的,但是由於某種原因,它在我的移動應用程序中會掛起。 因此,我更改了服務器端代碼,以實際創建和更新實際的JSON文件,現在一切正常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM