AssetBundleWebLoader.cs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. using System;
  2. using System.IO;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using UnityEngine;
  6. using UnityEngine.Networking;
  7. namespace YooAsset
  8. {
  9. internal sealed class AssetBundleWebLoader : AssetBundleLoaderBase
  10. {
  11. private enum ESteps
  12. {
  13. None = 0,
  14. Download,
  15. CheckDownload,
  16. LoadCacheFile,
  17. CheckLoadCacheFile,
  18. LoadWebFile,
  19. CheckLoadWebFile,
  20. TryLoadWebFile,
  21. Done,
  22. }
  23. private ESteps _steps = ESteps.None;
  24. private float _tryTimer = 0;
  25. private string _fileLoadPath;
  26. private bool _isShowWaitForAsyncError = false;
  27. private DownloaderBase _downloader;
  28. private UnityWebRequest _webRequest;
  29. private AssetBundleCreateRequest _createRequest;
  30. public AssetBundleWebLoader(BundleInfo bundleInfo) : base(bundleInfo)
  31. {
  32. }
  33. /// <summary>
  34. /// 轮询更新
  35. /// </summary>
  36. public override void Update()
  37. {
  38. if (_steps == ESteps.Done)
  39. return;
  40. if (_steps == ESteps.None)
  41. {
  42. if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromRemote)
  43. {
  44. _steps = ESteps.Download;
  45. _fileLoadPath = MainBundleInfo.Bundle.CachedFilePath;
  46. }
  47. else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromStreaming)
  48. {
  49. _steps = ESteps.LoadWebFile;
  50. _fileLoadPath = MainBundleInfo.Bundle.StreamingFilePath;
  51. }
  52. else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromCache)
  53. {
  54. _steps = ESteps.LoadCacheFile;
  55. _fileLoadPath = MainBundleInfo.Bundle.CachedFilePath;
  56. }
  57. else
  58. {
  59. throw new System.NotImplementedException(MainBundleInfo.LoadMode.ToString());
  60. }
  61. }
  62. // 1. 从服务器下载
  63. if (_steps == ESteps.Download)
  64. {
  65. int failedTryAgain = int.MaxValue;
  66. _downloader = DownloadSystem.BeginDownload(MainBundleInfo, failedTryAgain);
  67. _steps = ESteps.CheckDownload;
  68. }
  69. // 2. 检测服务器下载结果
  70. if (_steps == ESteps.CheckDownload)
  71. {
  72. if (_downloader.IsDone() == false)
  73. return;
  74. if (_downloader.HasError())
  75. {
  76. _steps = ESteps.Done;
  77. Status = EStatus.Failed;
  78. LastError = _downloader.GetLastError();
  79. }
  80. else
  81. {
  82. _steps = ESteps.LoadCacheFile;
  83. }
  84. }
  85. // 3. 从本地缓存里加载AssetBundle
  86. if (_steps == ESteps.LoadCacheFile)
  87. {
  88. #if UNITY_EDITOR
  89. // 注意:Unity2017.4编辑器模式下,如果AssetBundle文件不存在会导致编辑器崩溃,这里做了预判。
  90. if (System.IO.File.Exists(_fileLoadPath) == false)
  91. {
  92. _steps = ESteps.Done;
  93. Status = EStatus.Failed;
  94. LastError = $"Not found assetBundle file : {_fileLoadPath}";
  95. YooLogger.Error(LastError);
  96. return;
  97. }
  98. #endif
  99. // Load assetBundle file
  100. if (MainBundleInfo.Bundle.IsEncrypted)
  101. {
  102. if (AssetSystem.DecryptionServices == null)
  103. throw new Exception($"{nameof(AssetBundleFileLoader)} need {nameof(IDecryptionServices)} : {MainBundleInfo.Bundle.BundleName}");
  104. DecryptionFileInfo fileInfo = new DecryptionFileInfo();
  105. fileInfo.BundleName = MainBundleInfo.Bundle.BundleName;
  106. fileInfo.FileHash = MainBundleInfo.Bundle.FileHash;
  107. ulong offset = AssetSystem.DecryptionServices.GetFileOffset(fileInfo);
  108. _createRequest = AssetBundle.LoadFromFileAsync(_fileLoadPath, 0, offset);
  109. }
  110. else
  111. {
  112. _createRequest = AssetBundle.LoadFromFileAsync(_fileLoadPath);
  113. }
  114. _steps = ESteps.CheckLoadCacheFile;
  115. }
  116. // 4. 检测AssetBundle加载结果
  117. if (_steps == ESteps.CheckLoadCacheFile)
  118. {
  119. if (_createRequest.isDone == false)
  120. return;
  121. CacheBundle = _createRequest.assetBundle;
  122. if (CacheBundle == null)
  123. {
  124. _steps = ESteps.Done;
  125. Status = EStatus.Failed;
  126. LastError = $"Failed to load AssetBundle file : {MainBundleInfo.Bundle.BundleName}";
  127. YooLogger.Error(LastError);
  128. // 注意:当缓存文件的校验等级为Low的时候,并不能保证缓存文件的完整性。
  129. // 在AssetBundle文件加载失败的情况下,我们需要重新验证文件的完整性!
  130. if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromCache)
  131. {
  132. string cacheLoadPath = MainBundleInfo.Bundle.CachedFilePath;
  133. if (CacheSystem.VerifyBundle(MainBundleInfo.Bundle, EVerifyLevel.High) != EVerifyResult.Succeed)
  134. {
  135. if (File.Exists(cacheLoadPath))
  136. {
  137. YooLogger.Error($"Delete the invalid cache file : {cacheLoadPath}");
  138. File.Delete(cacheLoadPath);
  139. }
  140. }
  141. }
  142. }
  143. else
  144. {
  145. _steps = ESteps.Done;
  146. Status = EStatus.Succeed;
  147. }
  148. }
  149. // 5. 从WEB网站获取AssetBundle文件
  150. if (_steps == ESteps.LoadWebFile)
  151. {
  152. _webRequest = UnityWebRequestAssetBundle.GetAssetBundle(_fileLoadPath, Hash128.Parse(MainBundleInfo.Bundle.FileHash));
  153. _webRequest.SendWebRequest();
  154. _steps = ESteps.CheckLoadWebFile;
  155. }
  156. // 6. 检测AssetBundle加载结果
  157. if (_steps == ESteps.CheckLoadWebFile)
  158. {
  159. if (_webRequest.isDone == false)
  160. return;
  161. #if UNITY_2020_1_OR_NEWER
  162. if (_webRequest.result != UnityWebRequest.Result.Success)
  163. #else
  164. if (_webRequest.isNetworkError || _webRequest.isHttpError)
  165. #endif
  166. {
  167. YooLogger.Warning($"Failed to get asset bundle from web : {_fileLoadPath} Error : {_webRequest.error}");
  168. _steps = ESteps.TryLoadWebFile;
  169. _tryTimer = 0;
  170. }
  171. else
  172. {
  173. CacheBundle = DownloadHandlerAssetBundle.GetContent(_webRequest);
  174. if (CacheBundle == null)
  175. {
  176. _steps = ESteps.Done;
  177. Status = EStatus.Failed;
  178. LastError = $"AssetBundle file is invalid : {MainBundleInfo.Bundle.BundleName}";
  179. YooLogger.Error(LastError);
  180. }
  181. else
  182. {
  183. _steps = ESteps.Done;
  184. Status = EStatus.Succeed;
  185. }
  186. }
  187. }
  188. // 7. 如果获取失败,重新尝试
  189. if (_steps == ESteps.TryLoadWebFile)
  190. {
  191. _tryTimer += Time.unscaledDeltaTime;
  192. if (_tryTimer > 1f)
  193. {
  194. _webRequest.Dispose();
  195. _webRequest = null;
  196. _steps = ESteps.LoadWebFile;
  197. }
  198. }
  199. }
  200. /// <summary>
  201. /// 主线程等待异步操作完毕
  202. /// </summary>
  203. public override void WaitForAsyncComplete()
  204. {
  205. if (_isShowWaitForAsyncError == false)
  206. {
  207. _isShowWaitForAsyncError = true;
  208. YooLogger.Error($"WebGL platform not support {nameof(WaitForAsyncComplete)} ! Use the async load method instead of the sync load method !");
  209. }
  210. }
  211. }
  212. }