AssetDownloader.cs 8.4 KB

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