2013-08-21 18 views
2

我試圖在發生超時時處置WWW對象。我使用下面的代碼:如果在Unity3d中發生超時,請處理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()

我不知道我在做什麼錯在這裏。

有人可以幫我嗎?

回答

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

使用 '使用',而不是手動處理,因爲它自動部署:

 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#

+0

爲什麼這會降低投票率?這是使用IDisposables的正確方法。 – arichards

相關問題