2017-02-25 19 views
1

我目前正在開發一款益智遊戲,並試圖製作一個自動更新程序。所以用戶可以在不手動下載最新版本的情況下更新他們的遊戲。版本檢查本身正在工作,但是當我試圖使用WWW(url)下載文件時,需要花費相當多的時間來下載,但是一旦我檢入了我的文件瀏覽器,它就創建了一個0字節的文件。而在OSX中,它實際上被立即刪除。File.WriteAllBytes正在創建一個0字節文件

這是我正在使用的代碼。

void UpdateGame(){ 
    string path = Application.dataPath; 
    if (Application.platform == RuntimePlatform.OSXPlayer) { 
     path += "/../../"; 
    } 
    else if (Application.platform == RuntimePlatform.WindowsPlayer) { 
     path += "/../"; 
    } 

    if (System.IO.File.Exists (path+"/Apo_Alpha.app")) { 
     Debug.Log ("File exists!"); 
     System.IO.File.Delete (path+"/Apo_Alpha.app"); 

    } 


     WWW www = new WWW ("https://www.dropbox.com/sh/aayo9iud7t98hgb/AACDqSST_-rT2jIfxq1Zc2SXa?dl=1"); 

    while (!www.isDone) { 
     Debug.Log ("Waiting for download"); 
    } 

     string fullPath = path+"/Apo_Alpha.app"; 
     System.IO.File.WriteAllBytes (fullPath, www.bytes); 

    Debug.Log ("Done downloading..."); 
    Debug.Log ("File downloaded at " + fullPath); 

} 

這是怎麼發生的?是否因爲我可能不得不等待這些字節被寫入?我很想在這裏獲得某種形式的幫助。我相信這只是一個小錯誤,但我無法在任何地方找到答案。 (URL的是正確的,我雙重檢查他們...)

+0

我不知道團結好,但'isDone'文件明確地說:「你不應該寫循環直到下載完成;使用協程代替。「 –

+0

只是一個註釋(與您的問題無關):檢查'File.Exist'不能確保它在下一行執行後仍然存在,或者您有適當的權限將其刪除。你仍然需要捕捉異常。 – Jens

回答

0

當我試圖下載使用WWW(URL)的文件,它需要相當長 一些時間來下載

這是因爲你正在阻塞主線程。這應該在協同程序中完成。

IEnumerator downLoadFromServer() 
{ 
    WWW www = new WWW("yourUrl"); 
    yield return www; 
    Debug.Log("Done downloading"); 

    byte[] yourBytes = www.bytes; 

    System.IO.File.WriteAllBytes(fullPath, yourBytes); 
} 

然後調用/與StartCoroutine(downLoadFromServer());

啓動協程現在,如果你想使用www.isDone,你必須在協程功能產生或統一主線程將凍結,直到該文件被下載。

這裏是www.isDone應如何使用的例子:

IEnumerator downLoadFromServer() 
{ 
    string url = "https://www.dropbox.com/sh/aayo9iud7t98hgb/AACDqSST_-rT2jIfxq1Zc2SXa?dl=1"; 

    WWW www = new WWW(url); 

    while (!www.isDone) 
    { 
     //Must yield below/wait for a frame 
     yield return null; 
    } 

    Debug.Log("Done downloading"); 

    byte[] yourBytes = www.bytes; 

    //Now Save it 
    System.IO.File.WriteAllBytes(fullPath, yourBytes); 
} 

最後,不要手動創建的路徑。不要做這樣的東西:

path += "/../";

使用Path.Combine做到這一點:

path = Path.Combine(path,"Other Folder"); 
+0

謝謝先生,這解決了我的問題!我一直有點IEnumerators堅持等。要習慣它。當你知道如何使用它時,它確實派上用場。 – Teddynieuws

+0

反正,謝謝你的回答! – Teddynieuws

+0

在線有許多協程教程。我建議看一下關於Unity的內容。 – Programmer