LocalLoadManager.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.Networking;
  5. public class LocalLoadManager : MonoSingleton<LocalLoadManager>
  6. {
  7. /// <summary>
  8. /// 已下载资源
  9. /// </summary>
  10. private Dictionary<string, byte[]> dicLoaclData = new Dictionary<string, byte[]>();
  11. public void LocalLoadMaterial(DownLoadMaterial downloadMaterial)
  12. {
  13. if (dicLoaclData.ContainsKey(downloadMaterial.localLoadPath))
  14. {
  15. MsgHandler.SendMsg(downloadMaterial.localLoadPath, new Msg(downloadMaterial.localLoadPath, dicLoaclData[downloadMaterial.localLoadPath]));
  16. }
  17. else
  18. StartCoroutine(DownloadFile(downloadMaterial));
  19. }
  20. private System.Collections.IEnumerator DownloadFile(DownLoadMaterial downloadMaterial)
  21. {
  22. bool isDownLoad;
  23. using (UnityWebRequest webRequest = new UnityWebRequest(downloadMaterial.localLoadPath, UnityWebRequest.kHttpVerbGET))
  24. {
  25. webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
  26. webRequest.SetRequestHeader("authorization", UserInfo.Instance.Token);
  27. webRequest.SetRequestHeader("Content-Type", "application/json");
  28. yield return webRequest.SendWebRequest();
  29. while (!webRequest.isDone)
  30. {
  31. // 此处可以显示下载进度条等UI操作
  32. //progress = webRequest.downloadProgress;
  33. //onProgress?.Invoke(progress);
  34. // Debug.Log("Download Progress: " + progress);
  35. yield return new WaitForFixedUpdate();
  36. }
  37. if (webRequest.isHttpError || webRequest.isNetworkError)
  38. {
  39. Debug.LogError("Download Failed: " + webRequest.error);
  40. // 下载失败
  41. //downLoadState = webRequest.error;
  42. isDownLoad = false;
  43. MsgHandler.SendMsg(downloadMaterial.localLoadPath, new Msg(downloadMaterial.localLoadPath,null));
  44. }
  45. else
  46. {
  47. Debug.Log(webRequest.isDone + " " + webRequest.downloadHandler.data.Length);
  48. // Debug.LogError("Download Failed: " + webRequest.error);
  49. dicLoaclData.Add(downloadMaterial.localLoadPath, webRequest.downloadHandler.data);
  50. isDownLoad = true;
  51. MsgHandler.SendMsg(downloadMaterial.localLoadPath, new Msg(downloadMaterial.localLoadPath, webRequest.downloadHandler.data));
  52. }
  53. }
  54. }
  55. }