3

如果发生超时,我正在尝试处理 WWW 对象。我正在使用以下代码:

WWW localWWW;

void Start ()
{
    stattTime = Time.time;

    nextChange = Time.time + rotationSpeed;

    StartCoroutine ("DownloadFile");

}

bool isStopped = false;
bool isDownloadStarted = false;
// Update is called once per frame
void Update ()
{   //2.0f as to simulate timeout
    if (Time.time > stattTime + 2.0f && !isStopped) {
        isStopped = true;
        isDownloadStarted = false;
        Debug.Log ("Downloading stopped");
        StopCoroutine ("DownloadFile");
        localWWW.Dispose ();

    }
    if (isDownloadStarted) {

    }

    if (Time.time > nextChange && isDownloadStarted) {
        Debug.Log ("Current Progress: " + localWWW.progress);
        nextChange = Time.time + rotationSpeed;
    }
}

IEnumerator DownloadFile ()
{
    isDownloadStarted = true;
    GetWWW ();
    Debug.Log ("Download started");
    yield return (localWWW==null?null:localWWW);
    Debug.Log ("Downlaod complete");
    if (localWWW != null) {
        if (string.IsNullOrEmpty (localWWW.error)) {
            Debug.Log (localWWW.data);
        }
    }
}

public void GetWWW ()
{
    localWWW = new WWW (@"http://www.sample.com");
}

但我得到了例外:

NullReferenceException:WWW 类已被释放。TestScript+c__Iterator2.MoveNext()

我不确定我在这里做错了什么。

有人可以帮我吗?

4

2 回答 2

3

localWWW永远不应该null,因为GetWWW总是返回一个新实例。

以下代码片段虽然丑陋,但应该可以帮助您入门。

float elapsedTime = 0.0f;
float waitTime = 2.5f;
bool isDownloading = false;
WWW theWWW = null;
void Update () {
    elapsedTime += Time.deltaTime;
    if(elapsedTime >= waitTime && isDownloading){
        StopCoroutine("Download");
        theWWW.Dispose();
    }
}

IEnumerator Download(string url){
    elapsedTime = 0.0f;
    isDownloading = true;

    theWWW = new WWW(url);
    yield return theWWW;

    Debug.Log("Download finished");
}
于 2013-08-21T17:00:23.327 回答
1

使用“使用”而不是手动处理,因为它会自动处理:

        using ( WWW www = new WWW( url, form ) ) {
            yield return www;
            // check for errors
            if ( www.error == null ) {
                Debug.LogWarning( "WWW Ok: " + www.text );
            } else {
                Debug.LogWarning( "WWW Error: " + www.error );
            }
        }

C#中“使用”的使用

于 2013-08-21T11:25:25.963 回答