繁体   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