AssetDownloader.cs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using UnityEngine;
  6. using UnityEngine.Networking;
  7. public class AssetDownloader : SingletonMono<AssetDownloader>
  8. {
  9. private Dictionary<DownloadTask, bool> tasks;
  10. private List<DownloadDataEntity> downloadDataEntities;
  11. private List<DownloadDataEntity> downloadSuccessDataEntities;
  12. private int curTaskNum;
  13. private int maxTasknum;
  14. public bool CancelDownLoad { get; set; }
  15. private void Awake()
  16. {
  17. Init();
  18. }
  19. void Start()
  20. {
  21. }
  22. void Update()
  23. {
  24. if (!CancelDownLoad && HasNotDownloadedEntity())
  25. {
  26. while (HasIdleTask())
  27. {
  28. DownloadTask task = FindIdleTask();
  29. //
  30. DownloadDataEntity entity = FindNotDownloadedEntityByFirst();
  31. if (entity != null)
  32. {
  33. task.CurDownloadEntity = entity;
  34. DownLoad(task);
  35. }
  36. }
  37. }
  38. }
  39. protected override void Dispose()
  40. {
  41. StopAllCoroutines();
  42. base.Dispose();
  43. }
  44. private void Init()
  45. {
  46. maxTasknum = DownloadMgr.Instance.DownloadTaskMaxNum;
  47. tasks = new Dictionary<DownloadTask, bool>(maxTasknum);
  48. downloadDataEntities = new List<DownloadDataEntity>();
  49. downloadSuccessDataEntities = new List<DownloadDataEntity>();
  50. for (int i = 0; i < maxTasknum; i++)
  51. {
  52. DownloadTask task = new DownloadTask();
  53. task.Callback = TaskCallback;
  54. tasks.Add(task, true);
  55. }
  56. curTaskNum = 0;
  57. CancelDownLoad = false;
  58. }
  59. private IEnumerator DownloadFile(string url, Action<UnityWebRequest> callback)
  60. {
  61. Debug.Log($"url = {url}");
  62. UnityWebRequest webRqst = UnityWebRequest.Get(url);
  63. float timeOut = Time.time;
  64. UnityWebRequestAsyncOperation asyncOperation = webRqst.SendWebRequest();
  65. float progress = 0;
  66. while (!webRqst.isDone)
  67. {
  68. if (progress < webRqst.downloadProgress)
  69. {
  70. timeOut = Time.time;
  71. progress = webRqst.downloadProgress;
  72. Debug.Log($"下载 {progress}% DownloadSize = {webRqst.downloadedBytes}");
  73. }
  74. if (Time.time - timeOut > DownloadMgr.TimeOut)
  75. {
  76. Debug.LogWarning("下载超时!!!");
  77. callback?.Invoke(null);
  78. yield break;
  79. }
  80. yield return null;
  81. }
  82. progress = webRqst.downloadProgress;
  83. //yield return asyncOperation;
  84. if (webRqst != null && webRqst.error == null)
  85. {
  86. Debug.Log($"[{url}] 下载完成");
  87. callback?.Invoke(webRqst);
  88. }
  89. else
  90. {
  91. callback?.Invoke(null);
  92. Debug.Log($"下载失败;Error = {webRqst.error}");
  93. Debug.Log("下载失败 Error url = " + url);
  94. }
  95. webRqst.Dispose();
  96. }
  97. private IEnumerator AssetLoadToLocal(string url, string toPath, Action<byte[]> callback)
  98. {
  99. Debug.Log(url);
  100. using (WWW www = new WWW(url))
  101. {
  102. yield return www;
  103. if (www.error == null)
  104. {
  105. string localPath = FileHelper.PathRemoveBack(toPath);
  106. FileHelper.CreateDir(localPath);
  107. using (FileStream fs = File.Create(toPath, www.bytes.Length))
  108. {
  109. fs.Write(www.bytes, 0, www.bytes.Length);
  110. fs.Close();
  111. callback?.Invoke(www.bytes);
  112. }
  113. }
  114. else
  115. {
  116. Debug.Log("WWW Error = "+www.error);
  117. Debug.Log("WWW Error url = " + url);
  118. callback?.Invoke(null);
  119. }
  120. }
  121. }
  122. private IEnumerator AssetLoad(string url, Action<byte[]> callback)
  123. {
  124. using (WWW www = new WWW(url))
  125. {
  126. Debug.Log("WWW Url = " + url);
  127. yield return www;
  128. if (www.error == null)
  129. {
  130. callback?.Invoke(www.bytes);
  131. }
  132. else
  133. {
  134. callback?.Invoke(null);
  135. }
  136. }
  137. }
  138. private void DownLoad(DownloadTask task)
  139. {
  140. SetTaskState(task, false);
  141. if (task.SetUrl())
  142. {
  143. StartCoroutine(task.Task());
  144. }
  145. }
  146. private void TaskCallback(DownloadTask task)
  147. {
  148. if (task.State == DownloadTaskState.DownloadSuccess)
  149. {
  150. OnDownloadSuccess(task.CurDownloadEntity);
  151. task.CurDownloadEntity.Callback?.Invoke(task);
  152. }
  153. else if (task.State == DownloadTaskState.Error)
  154. {
  155. task.CurDownloadEntity.Callback?.Invoke(null);
  156. }
  157. SetTaskState(task, true);
  158. }
  159. private void SetTaskState(DownloadTask task, bool isIdle)
  160. {
  161. if (tasks.ContainsKey(task))
  162. {
  163. tasks[task] = isIdle;
  164. }
  165. if (isIdle)
  166. {
  167. curTaskNum--;
  168. }
  169. else
  170. {
  171. curTaskNum++;
  172. }
  173. }
  174. private DownloadDataEntity FindNotDownloadedEntityByFirst()
  175. {
  176. DownloadDataEntity entity = null;
  177. int size = downloadDataEntities.Count;
  178. for (int i = 0; i < size; i++)
  179. {
  180. if (downloadDataEntities[i].State == DownloadTaskState.None)
  181. {
  182. entity = downloadDataEntities[i];
  183. break;
  184. }
  185. }
  186. return entity;
  187. }
  188. private DownloadTask FindIdleTask()
  189. {
  190. DownloadTask idletask = null;
  191. foreach (var item in tasks)
  192. {
  193. if (item.Value == true)
  194. {
  195. idletask = item.Key;
  196. }
  197. }
  198. return idletask;
  199. }
  200. private void OnDownloadSuccess(DownloadDataEntity entity)
  201. {
  202. downloadSuccessDataEntities.Add(entity);
  203. downloadDataEntities.Remove(entity);
  204. }
  205. public bool HasIdleTask()
  206. {
  207. return curTaskNum < maxTasknum;
  208. }
  209. public bool HasNotDownloadedEntity()
  210. {
  211. return downloadDataEntities != null && downloadDataEntities.Count > 0;
  212. }
  213. public void AddDownloadTask(DownloadDataEntity dataEntity)
  214. {
  215. if (!downloadDataEntities.Contains(dataEntity) && !downloadSuccessDataEntities.Contains(dataEntity))
  216. {
  217. downloadDataEntities.Add(dataEntity);
  218. }
  219. }
  220. public void AddDownloadTasks(List<DownloadDataEntity> dataEntities)
  221. {
  222. downloadDataEntities.AddRange(dataEntities);
  223. }
  224. public void DownLoadFileByCoroutine(string url, Action<UnityWebRequest> callback)
  225. {
  226. StartCoroutine(DownloadFile(url, callback));
  227. }
  228. public void AssetLoadToLocalByCorutine(string url, string toPath, Action<byte[]> callback = null)
  229. {
  230. StartCoroutine(AssetLoadToLocal(url, toPath, callback));
  231. }
  232. public void AssetLoadByCorutine(string url, Action<byte[]> callback = null)
  233. {
  234. StartCoroutine(AssetLoad(url, callback));
  235. }
  236. public void DoByCorutine(Func<IEnumerator> callback)
  237. {
  238. if (callback != null)
  239. StartCoroutine(callback.Invoke());
  240. }
  241. public void ClearTasks()
  242. {
  243. downloadDataEntities.Clear();
  244. downloadSuccessDataEntities.Clear();
  245. }
  246. }