AssetDownloader.cs 8.2 KB

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