如果在Unity3d中发生超时,则处置WWW

时间:2013-08-21 09:31:58

标签: c# unity3d coroutine

如果发生超时,我正在尝试处理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()

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

有人可以帮助我吗?

2 个答案:

答案 0 :(得分: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");
}

答案 1 :(得分: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 );
            }
        }

Uses of "using" in C#