Unity 使用UnityWebRequest問題小結

UnityWebRequest是自帶的下載資源的api,優點顯而易見:封裝好,簡單用,兼容性跨平臺非常好。缺點也顯而易見:可拓展性差

下載小文件通常使用下面的方法:

   public IEnumerator DownloadFile(string url, string contentName)
    {
        string downloadFileName = "";
#if UNITY_EDITOR
        downloadFileName = Path.Combine(Application.dataPath, contentName);
#elif UNITY_ANDROID
        downloadFileName = Path.Combine(Application.persistentDataPath, contentName);
#endif
        using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
        {
            yield return webRequest.SendWebRequest();
            if (webRequest.isNetworkError)
            {
                Debug.LogError(webRequest.error);
            }
            else
            {
                DownloadHandler fileHandler = webRequest.downloadHandler;
                using (MemoryStream memory = new MemoryStream(fileHandler.data))
                {
                    byte[] buffer = new byte[1024 * 1024];
                    FileStream file = File.Open(downloadFileName, FileMode.OpenOrCreate);
                    int readBytes;
                    while ((readBytes = memory.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        file.Write(buffer, 0, readBytes);
                    }
                    file.Close();
                }
            }
        }
    }
 

這樣的下載方式下載小文件時基本沒有任何問題,但如果是大文件特別是移動端下載的時候就有可能直接崩潰了。因爲下載的時候是首先存在內存中,移動端容易內存不足,出現崩潰的情況很常見。

解決辦法:使用DownloadHandlerFile函數,可以直接將文件下載到外存,即可解決下載大文件崩潰的問題

 public IEnumerator DownloadVideoFile01(Uri uri, string downloadFileName, Slider sliderProgress )
    {
        using (UnityWebRequest downloader = UnityWebRequest.Get(uri))
        {
            downloader.downloadHandler = new DownloadHandlerFile(downloadFileName);//直接將文件下載到外存
 
            print("開始下載");
            downloader.SendWebRequest();
            print("同步進度條");
            while (!downloader.isDone)
            {
                //print(downloader.downloadProgress);
                sliderProgress.value = downloader.downloadProgress;
                sliderProgress.GetComponentInChildren<Text>().text = (downloader.downloadProgress* 100).ToString("F2") + "%";
                yield return null;
            }
 
            if (downloader.error != null)
            {
                Debug.LogError(downloader.error);
            }
            else
            {
                print("下載結束");
                sliderProgress.value = 1f;
                sliderProgress.GetComponentInChildren<Text>().text = 100.ToString("F2") + "%";
            }
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章