XMUnityAssetBundleManager.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. namespace CommonUnity3D.XMUnity.LoadUtil
  5. {
  6. /// <summary>
  7. /// XMUnityAssetBundle加载管理器.
  8. /// </summary>
  9. public class XMUnityAssetBundleManager : MonoBehaviour
  10. {
  11. private static XMUnityAssetBundleManager mInstance = null;
  12. private Dictionary<string, XMUnityAssetBundle> mABMap = null;
  13. private Dictionary<string, XMUnityABLoadAdapter> mLoadTaskMap = null;
  14. public AssetBundleManifest Manifest { get; private set; }
  15. public List<Shader> ShaderList { get; private set; }
  16. private Dictionary<string, List<string>> mDepsList = new Dictionary<string, List<string>>();
  17. public int PrefabCapacity = 50;
  18. private bool mNeedCleanUp = false;
  19. private List<XMUnityABLoadAdapter> mTempLoadTask = null;
  20. private AsyncOperation mUnloadOp = null;
  21. private bool mNeedUnload = false;
  22. void Awake()
  23. {
  24. mInstance = this;
  25. Init();
  26. }
  27. void Start()
  28. {
  29. }
  30. void Update()
  31. {
  32. //检查加载任务
  33. mTempLoadTask = new List<XMUnityABLoadAdapter>(mLoadTaskMap.Values);
  34. var iter = mTempLoadTask.GetEnumerator();
  35. while (iter.MoveNext())
  36. {
  37. if(iter.Current.OnAdapterUpdate())
  38. {
  39. iter.Current.Dispose();
  40. mLoadTaskMap.Remove(iter.Current.GetURL());
  41. }
  42. }
  43. mTempLoadTask.Clear();
  44. //是否存在加载任务
  45. bool isLoading = false;
  46. if (mLoadTaskMap.Count == 0)
  47. {
  48. var item = mABMap.GetEnumerator();
  49. while (item.MoveNext())
  50. {
  51. if (item.Current.Value.BundleStatus == XMUnityAssetBundle.Status.LoadAsset || item.Current.Value.BundleStatus == XMUnityAssetBundle.Status.LoadDep)
  52. {
  53. isLoading = true;
  54. break;
  55. }
  56. }
  57. }
  58. else
  59. {
  60. isLoading = true;
  61. }
  62. //在合适的时候执行Cleanup
  63. if (!isLoading && mNeedCleanUp)
  64. {
  65. CleanAssetBundleMap(false);
  66. //Resources.UnloadUnusedAssets ();
  67. System.GC.Collect();
  68. mNeedCleanUp = false;
  69. }
  70. //检查unload进度
  71. if(mUnloadOp != null && mUnloadOp.isDone)
  72. {
  73. mUnloadOp = null;
  74. }
  75. //在合适的时候执行unload
  76. if (!isLoading && mNeedUnload)
  77. {
  78. mUnloadOp = Resources.UnloadUnusedAssets();
  79. mNeedUnload = false;
  80. }
  81. }
  82. private void Init()
  83. {
  84. mABMap = new Dictionary<string, XMUnityAssetBundle>();
  85. mLoadTaskMap = new Dictionary<string, XMUnityABLoadAdapter>();
  86. mTempLoadTask = new List<XMUnityABLoadAdapter>();
  87. ShaderList = new List<Shader>();
  88. StartLoadManifest();
  89. StartLoadShaderList();
  90. }
  91. void StartLoadManifest()
  92. {
  93. XMUnityABLoadAdapter load = new XMUnityABLoadAdapter();
  94. load.LoadAsync = false;
  95. load.SetFinishCallBack(OnManifestFinish);
  96. load.Load("/res/" + GetPlatformForAssetBundles(), null);
  97. StartCoroutine(CheckLoadManifest(load));
  98. }
  99. IEnumerator CheckLoadManifest(XMUnityABLoadAdapter load)
  100. {
  101. while (!load.HasDone)
  102. {
  103. load.OnAdapterUpdate();
  104. yield return null;
  105. }
  106. }
  107. private void OnManifestFinish(XMUnityABLoadAdapter adapter)
  108. {
  109. if (adapter.GetAssetBundle() != null)
  110. {
  111. Manifest = adapter.GetAssetBundle().LoadAsset<AssetBundleManifest>("AssetBundleManifest");
  112. }
  113. else
  114. {
  115. Debug.LogError("XMUnityAssetBundleManager can not find Manifest");
  116. }
  117. }
  118. void StartLoadShaderList()
  119. {
  120. XMUnityABLoadAdapter load = new XMUnityABLoadAdapter();
  121. load.LoadAsync = false;
  122. load.SetFinishCallBack(OnShaderListFinish);
  123. load.Load("/res/shaderslist.assetbundles", null);
  124. StartCoroutine(CheckLoadShaderList(load));
  125. }
  126. IEnumerator CheckLoadShaderList(XMUnityABLoadAdapter load)
  127. {
  128. while (!load.HasDone)
  129. {
  130. load.OnAdapterUpdate();
  131. yield return null;
  132. }
  133. }
  134. private void OnShaderListFinish(XMUnityABLoadAdapter adapter)
  135. {
  136. if (adapter.GetAssetBundle() != null)
  137. {
  138. Object[] shaderobject = adapter.GetAssetBundle().LoadAllAssets();
  139. foreach (Object sb in shaderobject)
  140. {
  141. if (sb is Shader)
  142. {
  143. ShaderList.Add((Shader)sb);
  144. }
  145. else
  146. {
  147. Debug.Log("ShaderList add dif type=" + sb.GetType());
  148. }
  149. }
  150. Shader.WarmupAllShaders();
  151. }
  152. else
  153. {
  154. Debug.LogWarning("XMUnityAssetBundleManager can not find ShaderList");
  155. }
  156. }
  157. public void Dispose()
  158. {
  159. CleanAssetBundleMap(true);
  160. mInstance = null;
  161. }
  162. public static XMUnityAssetBundleManager GetInstance()
  163. {
  164. if (mInstance == null)
  165. {
  166. Debug.LogError("XMUnityAssetBundleManager must create before use");
  167. }
  168. return mInstance;
  169. }
  170. public void UnloadUnusedAssets()
  171. {
  172. if(mUnloadOp == null)
  173. {
  174. mNeedUnload = true;
  175. }
  176. }
  177. public List<string> GetDepList(string name)
  178. {
  179. name = name.ToLower();
  180. string dep_key = name.ToLower().Replace("/res/", "");
  181. if (!mDepsList.ContainsKey(name))
  182. {
  183. string[] deps = Manifest.GetAllDependencies(dep_key);
  184. List<string> ds = new List<string>(deps.Length);
  185. for (int i = 0; i < deps.Length; i++)
  186. {
  187. if(deps[i] != "shaderslist.assetbundles")
  188. {
  189. string key = "/res/" + deps[i];
  190. //if (name != key)
  191. //{
  192. ds.Add(key);
  193. //}
  194. //else
  195. //{
  196. // Debug.LogError("what the fuck");
  197. //}
  198. }
  199. }
  200. mDepsList[name] = (ds);
  201. }
  202. return mDepsList[name];
  203. }
  204. public void GetAssetBundle(string name, XMUnityABLoadAdapter.XMUnityLoadAdapterCallBack callBack, bool async = true)
  205. {
  206. name = name.ToLower();
  207. XMUnityAssetBundle ab = null;
  208. XMUnityABLoadAdapter adapter = null;
  209. if (mABMap.TryGetValue(name, out ab)) //从AB中寻找AssetBundle.
  210. {
  211. if (callBack != null)
  212. {
  213. callBack.Invoke(ab);
  214. //return null;
  215. }
  216. }
  217. else if (mLoadTaskMap.TryGetValue(name, out adapter)) //从正在加载的map中寻找.
  218. {
  219. if (callBack != null)
  220. {
  221. adapter.AddCallBack(callBack);
  222. }
  223. //return null;
  224. }
  225. else //创建加载器.
  226. {
  227. XMUnityABLoadAdapter load = new XMUnityABLoadAdapter();
  228. load.LoadAsync = async;
  229. mLoadTaskMap.Add(name, load);
  230. load.SetFinishCallBack(OnAdapterFinish);
  231. load.Load(name, callBack);
  232. //return load;
  233. }
  234. //return null;
  235. }
  236. public AssetBundle GetAssetBundle(string name)
  237. {
  238. name = name.ToLower();
  239. XMUnityAssetBundle ret = null;
  240. mABMap.TryGetValue(name, out ret);
  241. return ret.AssetBundle;
  242. }
  243. public XMUnityAssetBundle GetXMUnityAssetBundle(string name)
  244. {
  245. name = name.ToLower();
  246. XMUnityAssetBundle ret = null;
  247. mABMap.TryGetValue(name, out ret);
  248. if (ret == null)
  249. {
  250. return null;
  251. }
  252. return ret;
  253. }
  254. public bool AddAssetBundle(string name, XMUnityAssetBundle ab)
  255. {
  256. if (!string.IsNullOrEmpty(name) && ab != null)
  257. {
  258. mABMap.Add(name, ab);
  259. return true;
  260. }
  261. Debug.Log("XMUnityAssetBundleManager AddAssetBundle Error: Invaild Data");
  262. return false;
  263. }
  264. /// <summary>
  265. /// 将remove操作push到一个队列中执行,只有当当前没有加载任务时才会触发.
  266. /// </summary>
  267. /// <param name="name"></param>
  268. /// <param name="isUnloadAll"></param>
  269. public void UnloadAssetBundle(string name, bool isUnloadAll = false, bool force = false)
  270. {
  271. XMUnityAssetBundle ab = null;
  272. if (mABMap.TryGetValue(name, out ab))
  273. {
  274. if (ab != null)
  275. {
  276. if(ab.BundleType == XMUnityAssetBundle.Type.DEP_ASSET)
  277. {
  278. Debug.LogError("Cant unload a dep assetbundle: " + name);
  279. }
  280. List<string> deps = GetDepList(name);
  281. foreach (var item in deps)
  282. {
  283. XMUnityAssetBundle mfab = null;
  284. if (mABMap.TryGetValue(item, out mfab))
  285. {
  286. if (mfab != null)
  287. {
  288. if (mfab.TryUnloadDep(name, isUnloadAll, force))
  289. {
  290. mABMap.Remove(item);
  291. }
  292. }
  293. }
  294. }
  295. UnloadAssetBundleImmediate(name, isUnloadAll, force);
  296. }
  297. }
  298. else
  299. {
  300. //通常只有切换场景时没有清除资源的情况下强制卸载了所有ab才会出,可以用来监控逻辑加载卸载成对的情况
  301. Debug.LogWarning("[策划,测试请无视]UnloadAssetBundle Error, bundle not exists: " + name);
  302. }
  303. }
  304. public void UnloadAssetBundleImmediate(string name, bool isUnloadAll, bool force = false)
  305. {
  306. // 内部自动处理
  307. XMUnityAssetBundle ab = null;
  308. if (mABMap.TryGetValue(name, out ab))
  309. {
  310. if (ab != null)
  311. {
  312. //TODO 销毁XMUnityAssetBundle,主要是缓存和prefab
  313. if (ab.Unload(isUnloadAll, force))
  314. {
  315. mABMap.Remove(name);
  316. }
  317. }
  318. }
  319. else
  320. {
  321. Debug.LogWarning("[策划,测试请无视]UnloadAssetBundleImmediate Error, bundle not exists: " + name);
  322. }
  323. }
  324. public void LoadDep(string name, bool loadABASync, bool loadAssetASync, XMUnityAssetBundle.LoadResCallBack callback, object userdata, string childAB)
  325. {
  326. XMUnityAssetBundleManager.GetInstance().GetAssetBundle(name, (XMUnityAssetBundle mfab) =>
  327. {
  328. if (mfab != null)
  329. {
  330. mfab.MarkAsDeps(childAB);
  331. }
  332. //else
  333. {
  334. callback(null, null, userdata, false);
  335. }
  336. }, loadABASync);
  337. }
  338. public void LoadAsset(string name, string asset, bool loadABASync, bool loadAssetASync, XMUnityAssetBundle.LoadResCallBack callback, object userdata, System.Type type = null)
  339. {
  340. GetAssetBundle(name, (XMUnityAssetBundle mfab) =>
  341. {
  342. if (mfab != null)
  343. {
  344. mfab.GetAsset(asset, loadAssetASync, callback, userdata, type);
  345. }
  346. else
  347. {
  348. callback(asset, null, userdata, false);
  349. }
  350. }, loadABASync);
  351. }
  352. public void LoadAsset(string name, bool loadABASync, bool loadAssetASync, XMUnityAssetBundle.LoadResCallBack callback, object userdata, System.Type type = null)
  353. {
  354. int starIndex = name.LastIndexOf('/') + 1;
  355. int length = name.Length - starIndex - ".assetbundles".Length;
  356. string objectName = name.Substring(starIndex, length);
  357. LoadAsset(name.ToLower(), objectName, loadABASync, loadAssetASync, callback, userdata, type);
  358. }
  359. public void CleanAssetBundleMap(bool isUnloadAll)
  360. {
  361. var temp = new Dictionary<string, XMUnityAssetBundle>();
  362. foreach (KeyValuePair<string, XMUnityAssetBundle> kvp in mABMap)
  363. {
  364. if (kvp.Value != null)
  365. {
  366. if(!kvp.Value.Unload(isUnloadAll, true))
  367. {
  368. temp.Add(kvp.Key, kvp.Value);
  369. }
  370. }
  371. }
  372. mABMap.Clear();
  373. mABMap = temp;
  374. AssetObject.ClearRefs();
  375. }
  376. public void CleanAssetBundleMapInQueue()
  377. {
  378. mNeedCleanUp = true;
  379. }
  380. private void OnAdapterFinish(XMUnityABLoadAdapter adapter)
  381. {
  382. XMUnityAssetBundle mfab = adapter.GetXMUnityAssetBundle();
  383. if (mfab != null)
  384. {
  385. mABMap.Add(adapter.GetURL(), mfab);
  386. }
  387. if (mLoadTaskMap.ContainsKey(adapter.GetURL()))
  388. {
  389. mLoadTaskMap.Remove(adapter.GetURL());
  390. }
  391. else
  392. {
  393. Debug.Log("XMUnityAssetBundleManager can not find Adapter");
  394. }
  395. adapter.DispatchCallBack();
  396. }
  397. public bool ContainsBundle(string name) { return mABMap.ContainsKey(name); }
  398. public static string GetPlatformForAssetBundles()
  399. {
  400. RuntimePlatform platform = Application.platform;
  401. switch (platform)
  402. {
  403. case RuntimePlatform.Android:
  404. return "android";
  405. case RuntimePlatform.IPhonePlayer:
  406. return "ios";
  407. case RuntimePlatform.WebGLPlayer:
  408. return "webgl";
  409. case RuntimePlatform.OSXWebPlayer:
  410. case RuntimePlatform.WindowsWebPlayer:
  411. return "standalonewindows";
  412. case RuntimePlatform.WindowsEditor:
  413. #if UNITY_ANDROID
  414. return "android";
  415. #else
  416. return "standalonewindows";
  417. #endif
  418. case RuntimePlatform.WindowsPlayer:
  419. return "standalonewindows";
  420. case RuntimePlatform.OSXPlayer:
  421. return "osx";
  422. default:
  423. return null;
  424. }
  425. }
  426. }
  427. }