AssetDownloader.cs 8.5 KB

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