DownLoadURLXRItem.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using UnityEngine;
  5. using UnityEngine.Networking;
  6. using static DownLoadXRManager;
  7. public class DownLoadURLXRItem : MonoBehaviour
  8. {
  9. public static Dictionary<string, List<DownLoadConfig>> downLoadingList = new Dictionary<string, List<DownLoadConfig>>();
  10. public void startDownload(DownLoadConfig config)
  11. {
  12. StartCoroutine(ReadStreamingAssetsFile(config));
  13. }
  14. IEnumerator ReadStreamingAssetsFile(DownLoadConfig config)
  15. {
  16. if (DownLoadXRManager.downLoadCache.ContainsKey(config.data.path))
  17. {
  18. config.bytes?.Invoke(DownLoadXRManager.downLoadCache[config.data.path]);
  19. yield return null;
  20. }
  21. else
  22. {
  23. if(downLoadingList.ContainsKey(config.data.path))
  24. {
  25. downLoadingList[config.data.path].Add(config);
  26. }
  27. else
  28. {
  29. downLoadingList.Add(config.data.path, new List<DownLoadConfig>());
  30. downLoadingList[config.data.path].Add(config);
  31. string filePath = config.data.path;
  32. Debug.Log("准备下载" + filePath);
  33. UnityWebRequest www = UnityWebRequest.Get(filePath);
  34. www.SendWebRequest();
  35. while (!www.isDone)
  36. {
  37. for (int i = 0; i <downLoadingList[config.data.path].Count; i++)
  38. {
  39. downLoadingList[config.data.path][i].presson?.Invoke(www.downloadProgress);
  40. }
  41. yield return null;
  42. }
  43. if (www.result != UnityWebRequest.Result.ConnectionError && www.isDone)
  44. {
  45. byte[] bytes = www.downloadHandler.data;
  46. for (int i = 0; i < downLoadingList[config.data.path].Count; i++)
  47. {
  48. downLoadingList[config.data.path][i].bytes?.Invoke(bytes);
  49. }
  50. if (!DownLoadXRManager.downLoadCache.ContainsKey(config.data.path))
  51. DownLoadXRManager.downLoadCache.Add(config.data.path, bytes);
  52. downLoadingList.Remove(config.data.path);
  53. }
  54. else
  55. {
  56. for (int i = 0; i < downLoadingList[config.data.path].Count; i++)
  57. {
  58. downLoadingList[config.data.path][i].bytes?.Invoke(null);
  59. }
  60. downLoadingList.Remove(config.data.path);
  61. }
  62. }
  63. }
  64. Destroy(this.gameObject);
  65. }
  66. }