简体   繁体   中英

Dispose WWW if timeout occurs in Unity3d

I am trying to dispose a WWW object if a timeout occurs. I am using following code:

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");
}

But I am getting exception:

NullReferenceException: WWW class has already been disposed. TestScript+c__Iterator2.MoveNext ()

I am not sure what I am doing wrong here.

Can anybody help me in this?

localWWW should never be null because GetWWW always returns a new instance.

The following snippet, though ugly, should get you started.

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");
}

use 'using' instead of dispose manually as it auto disposes:

        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#

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM