ResourcesComponent.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using UnityEngine;
  7. #if UNITY_EDITOR
  8. using UnityEditor;
  9. #endif
  10. namespace ET
  11. {
  12. [ObjectSystem]
  13. public class ABInfoAwakeSystem: AwakeSystem<ABInfo, string, AssetBundle>
  14. {
  15. public override void Awake(ABInfo self, string abName, AssetBundle a)
  16. {
  17. self.AssetBundle = a;
  18. self.Name = abName;
  19. self.RefCount = 1;
  20. }
  21. }
  22. [ObjectSystem]
  23. public class ABInfoDestroySystem: DestroySystem<ABInfo>
  24. {
  25. public override void Destroy(ABInfo self)
  26. {
  27. //Log.Debug($"desdroy assetbundle: {this.Name}");
  28. self.RefCount = 0;
  29. self.Name = "";
  30. }
  31. }
  32. public class ABInfo: Entity
  33. {
  34. public string Name
  35. {
  36. get;
  37. set;
  38. }
  39. public int RefCount
  40. {
  41. get;
  42. set;
  43. }
  44. public AssetBundle AssetBundle;
  45. public void Destroy(bool unload = true)
  46. {
  47. if (this.AssetBundle != null)
  48. {
  49. this.AssetBundle.Unload(unload);
  50. }
  51. this.Dispose();
  52. }
  53. }
  54. // 用于字符串转换,减少GC
  55. public static class AssetBundleHelper
  56. {
  57. public static string IntToString(this int value)
  58. {
  59. string result;
  60. if (ResourcesComponent.Instance.IntToStringDict.TryGetValue(value, out result))
  61. {
  62. return result;
  63. }
  64. result = value.ToString();
  65. ResourcesComponent.Instance.IntToStringDict[value] = result;
  66. return result;
  67. }
  68. public static string StringToAB(this string value)
  69. {
  70. string result;
  71. if (ResourcesComponent.Instance.StringToABDict.TryGetValue(value, out result))
  72. {
  73. return result;
  74. }
  75. result = value + ".unity3d";
  76. ResourcesComponent.Instance.StringToABDict[value] = result;
  77. return result;
  78. }
  79. public static string IntToAB(this int value)
  80. {
  81. return value.IntToString().StringToAB();
  82. }
  83. public static string BundleNameToLower(this string value)
  84. {
  85. string result;
  86. if (ResourcesComponent.Instance.BundleNameToLowerDict.TryGetValue(value, out result))
  87. {
  88. return result;
  89. }
  90. result = value.ToLower();
  91. ResourcesComponent.Instance.BundleNameToLowerDict[value] = result;
  92. return result;
  93. }
  94. }
  95. [ObjectSystem]
  96. public class ResourcesComponentAwakeSystem: AwakeSystem<ResourcesComponent>
  97. {
  98. public override void Awake(ResourcesComponent self)
  99. {
  100. self.Awake();
  101. }
  102. }
  103. public class ResourcesComponent: Entity
  104. {
  105. public static ResourcesComponent Instance
  106. {
  107. get;
  108. set;
  109. }
  110. public AssetBundleManifest AssetBundleManifestObject
  111. {
  112. get;
  113. set;
  114. }
  115. public Dictionary<int, string> IntToStringDict = new Dictionary<int, string>();
  116. public Dictionary<string, string> StringToABDict = new Dictionary<string, string>();
  117. public Dictionary<string, string> BundleNameToLowerDict = new Dictionary<string, string>() { { "StreamingAssets", "StreamingAssets" } };
  118. private readonly Dictionary<string, Dictionary<string, UnityEngine.Object>> resourceCache = new Dictionary<string, Dictionary<string, UnityEngine.Object>>();
  119. private readonly Dictionary<string, ABInfo> bundles = new Dictionary<string, ABInfo>();
  120. public void Awake()
  121. {
  122. Instance = this;
  123. if (Define.IsAsync)
  124. {
  125. LoadOneBundle("StreamingAssets");
  126. AssetBundleManifestObject = (AssetBundleManifest)GetAsset("StreamingAssets", "AssetBundleManifest");
  127. }
  128. }
  129. public override void Dispose()
  130. {
  131. if (this.IsDisposed)
  132. {
  133. return;
  134. }
  135. base.Dispose();
  136. Instance = null;
  137. foreach (KeyValuePair<string, ABInfo> abInfo in this.bundles)
  138. {
  139. abInfo.Value.Destroy();
  140. }
  141. this.bundles.Clear();
  142. this.resourceCache.Clear();
  143. this.IntToStringDict.Clear();
  144. this.StringToABDict.Clear();
  145. this.BundleNameToLowerDict.Clear();
  146. }
  147. private string[] GetDependencies(string assetBundleName, bool isScene = false)
  148. {
  149. string[] dependencies = new string[0];
  150. if (DependenciesCache.TryGetValue(assetBundleName, out dependencies))
  151. {
  152. return dependencies;
  153. }
  154. if (!Define.IsAsync)
  155. {
  156. #if UNITY_EDITOR
  157. if (isScene == false)
  158. {
  159. dependencies = AssetDatabase.GetAssetBundleDependencies(assetBundleName, true);
  160. }
  161. #endif
  162. }
  163. else
  164. {
  165. dependencies = this.AssetBundleManifestObject.GetAllDependencies(assetBundleName);
  166. }
  167. DependenciesCache.Add(assetBundleName, dependencies);
  168. return dependencies;
  169. }
  170. public string[] GetSortedDependencies(string assetBundleName, bool isScene = false)
  171. {
  172. Dictionary<string, int> info = new Dictionary<string, int>();
  173. List<string> parents = new List<string>();
  174. CollectDependencies(parents, assetBundleName, info, isScene);
  175. string[] ss = info.OrderBy(x => x.Value).Select(x => x.Key).ToArray();
  176. return ss;
  177. }
  178. private void CollectDependencies(List<string> parents, string assetBundleName, Dictionary<string, int> info, bool isScene = false)
  179. {
  180. parents.Add(assetBundleName);
  181. string[] deps = GetDependencies(assetBundleName, isScene);
  182. foreach (string parent in parents)
  183. {
  184. if (!info.ContainsKey(parent))
  185. {
  186. info[parent] = 0;
  187. }
  188. info[parent] += deps.Length;
  189. }
  190. foreach (string dep in deps)
  191. {
  192. if (parents.Contains(dep))
  193. {
  194. throw new Exception($"包有循环依赖,请重新标记: {assetBundleName} {dep}");
  195. }
  196. CollectDependencies(parents, dep, info, isScene);
  197. }
  198. parents.RemoveAt(parents.Count - 1);
  199. }
  200. // 缓存包依赖,不用每次计算
  201. public Dictionary<string, string[]> DependenciesCache = new Dictionary<string, string[]>();
  202. public bool Contains(string bundleName)
  203. {
  204. return this.bundles.ContainsKey(bundleName);
  205. }
  206. public Dictionary<string, UnityEngine.Object> GetBundleAll(string bundleName)
  207. {
  208. Dictionary<string, UnityEngine.Object> dict;
  209. if (!this.resourceCache.TryGetValue(bundleName.BundleNameToLower(), out dict))
  210. {
  211. throw new Exception($"not found asset: {bundleName}");
  212. }
  213. return dict;
  214. }
  215. public UnityEngine.Object GetAsset(string bundleName, string prefab)
  216. {
  217. Dictionary<string, UnityEngine.Object> dict;
  218. if (!this.resourceCache.TryGetValue(bundleName.BundleNameToLower(), out dict))
  219. {
  220. throw new Exception($"not found asset: {bundleName} {prefab}");
  221. }
  222. UnityEngine.Object resource = null;
  223. if (!dict.TryGetValue(prefab, out resource))
  224. {
  225. throw new Exception($"not found asset: {bundleName} {prefab}");
  226. }
  227. return resource;
  228. }
  229. public async ETTask UnloadBundles(List<string> bundleList, bool unload = true)
  230. {
  231. int i = 0;
  232. foreach (string bundle in bundleList)
  233. {
  234. using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.Resources, bundle.GetHashCode()))
  235. {
  236. if (++i % 5 == 0)
  237. {
  238. await TimerComponent.Instance.WaitFrameAsync();
  239. }
  240. this.UnloadBundle(bundle, unload);
  241. }
  242. }
  243. }
  244. // 只允许场景设置unload为false
  245. public void UnloadBundle(string assetBundleName, bool unload = true)
  246. {
  247. assetBundleName = assetBundleName.BundleNameToLower();
  248. string[] dependencies = GetSortedDependencies(assetBundleName);
  249. //Log.Debug($"-----------dep unload start {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  250. foreach (string dependency in dependencies)
  251. {
  252. this.UnloadOneBundle(dependency, unload);
  253. }
  254. //Log.Debug($"-----------dep unload finish {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  255. }
  256. private void UnloadOneBundle(string assetBundleName, bool unload = true)
  257. {
  258. assetBundleName = assetBundleName.BundleNameToLower();
  259. ABInfo abInfo;
  260. if (!this.bundles.TryGetValue(assetBundleName, out abInfo))
  261. {
  262. return;
  263. }
  264. //Log.Debug($"---------------unload one bundle {assetBundleName} refcount: {abInfo.RefCount - 1}");
  265. --abInfo.RefCount;
  266. if (abInfo.RefCount > 0)
  267. {
  268. return;
  269. }
  270. //Log.Debug($"---------------truly unload one bundle {assetBundleName} refcount: {abInfo.RefCount}");
  271. this.bundles.Remove(assetBundleName);
  272. this.resourceCache.Remove(assetBundleName);
  273. abInfo.Destroy(unload);
  274. // Log.Debug($"cache count: {this.cacheDictionary.Count}");
  275. }
  276. /// <summary>
  277. /// 同步加载assetbundle
  278. /// </summary>
  279. /// <param name="assetBundleName"></param>
  280. /// <returns></returns>
  281. public void LoadBundle(string assetBundleName)
  282. {
  283. assetBundleName = assetBundleName.ToLower();
  284. string[] dependencies = GetSortedDependencies(assetBundleName);
  285. //Log.Debug($"-----------dep load start {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  286. foreach (string dependency in dependencies)
  287. {
  288. if (string.IsNullOrEmpty(dependency))
  289. {
  290. continue;
  291. }
  292. this.LoadOneBundle(dependency);
  293. }
  294. //Log.Debug($"-----------dep load finish {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  295. }
  296. public void AddResource(string bundleName, string assetName, UnityEngine.Object resource)
  297. {
  298. Dictionary<string, UnityEngine.Object> dict;
  299. if (!this.resourceCache.TryGetValue(bundleName.BundleNameToLower(), out dict))
  300. {
  301. dict = new Dictionary<string, UnityEngine.Object>();
  302. this.resourceCache[bundleName] = dict;
  303. }
  304. dict[assetName] = resource;
  305. }
  306. private void LoadOneBundle(string assetBundleName)
  307. {
  308. assetBundleName = assetBundleName.BundleNameToLower();
  309. ABInfo abInfo;
  310. if (this.bundles.TryGetValue(assetBundleName, out abInfo))
  311. {
  312. ++abInfo.RefCount;
  313. //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
  314. return;
  315. }
  316. if (!Define.IsAsync)
  317. {
  318. string[] realPath = null;
  319. #if UNITY_EDITOR
  320. realPath = AssetDatabase.GetAssetPathsFromAssetBundle(assetBundleName);
  321. foreach (string s in realPath)
  322. {
  323. string assetName = Path.GetFileNameWithoutExtension(s);
  324. UnityEngine.Object resource = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(s);
  325. AddResource(assetBundleName, assetName, resource);
  326. }
  327. if (realPath.Length > 0)
  328. {
  329. abInfo = EntityFactory.CreateWithParent<ABInfo, string, AssetBundle>(this, assetBundleName, null);
  330. this.bundles[assetBundleName] = abInfo;
  331. //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
  332. }
  333. else
  334. {
  335. Log.Error($"assets bundle not found: {assetBundleName}");
  336. }
  337. #endif
  338. return;
  339. }
  340. string p = Path.Combine(PathHelper.AppHotfixResPath, assetBundleName);
  341. AssetBundle assetBundle = null;
  342. if (File.Exists(p))
  343. {
  344. assetBundle = AssetBundle.LoadFromFile(p);
  345. }
  346. else
  347. {
  348. p = Path.Combine(PathHelper.AppResPath, assetBundleName);
  349. assetBundle = AssetBundle.LoadFromFile(p);
  350. }
  351. if (assetBundle == null)
  352. {
  353. // 获取资源的时候会抛异常,这个地方不直接抛异常,因为有些地方需要Load之后判断是否Load成功
  354. Log.Warning($"assets bundle not found: {assetBundleName}");
  355. return;
  356. }
  357. if (!assetBundle.isStreamedSceneAssetBundle)
  358. {
  359. // 异步load资源到内存cache住
  360. UnityEngine.Object[] assets = assetBundle.LoadAllAssets();
  361. foreach (UnityEngine.Object asset in assets)
  362. {
  363. AddResource(assetBundleName, asset.name, asset);
  364. }
  365. }
  366. abInfo = EntityFactory.CreateWithParent<ABInfo, string, AssetBundle>(this, assetBundleName, assetBundle);
  367. this.bundles[assetBundleName] = abInfo;
  368. //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
  369. }
  370. /// <summary>
  371. /// 异步加载assetbundle
  372. /// </summary>
  373. /// <param name="assetBundleName"></param>
  374. /// <param name="isScene"></param>
  375. /// <returns></returns>
  376. public async ETTask LoadBundleAsync(string assetBundleName, bool isScene = false)
  377. {
  378. assetBundleName = assetBundleName.BundleNameToLower();
  379. string[] dependencies = GetSortedDependencies(assetBundleName);
  380. //Log.Debug($"-----------dep load async start {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  381. using var tasts = ListComponent<ETTask>.Create();
  382. async ETTask loadDependency(string dependency)
  383. {
  384. using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.Resources, dependency.GetHashCode()))
  385. {
  386. await this.LoadOneBundleAsync(dependency, isScene);
  387. }
  388. }
  389. foreach (string dependency in dependencies)
  390. {
  391. if (string.IsNullOrEmpty(dependency))
  392. {
  393. continue;
  394. }
  395. tasts.List.Add(loadDependency(dependency));
  396. }
  397. await ETTaskHelper.WaitAll(tasts.List);
  398. }
  399. private async ETTask LoadOneBundleAsync(string assetBundleName, bool isScene)
  400. {
  401. assetBundleName = assetBundleName.BundleNameToLower();
  402. ABInfo abInfo;
  403. if (this.bundles.TryGetValue(assetBundleName, out abInfo))
  404. {
  405. ++abInfo.RefCount;
  406. //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
  407. return;
  408. }
  409. string p = "";
  410. AssetBundle assetBundle = null;
  411. if (!Define.IsAsync)
  412. {
  413. #if UNITY_EDITOR
  414. if (isScene)
  415. {
  416. p = Path.Combine(Application.dataPath, "../SceneBundle/", assetBundleName);
  417. if (File.Exists(p)) // 如果场景有预先打包
  418. {
  419. using (AssetsBundleLoaderAsync assetsBundleLoaderAsync = EntityFactory.CreateWithParent<AssetsBundleLoaderAsync>(this))
  420. {
  421. assetBundle = await assetsBundleLoaderAsync.LoadAsync(p);
  422. }
  423. if (assetBundle == null)
  424. {
  425. // 获取资源的时候会抛异常,这个地方不直接抛异常,因为有些地方需要Load之后判断是否Load成功
  426. Log.Warning($"Scene bundle not found: {assetBundleName}");
  427. return;
  428. }
  429. abInfo = EntityFactory.CreateWithParent<ABInfo, string, AssetBundle>(this, assetBundleName, assetBundle);
  430. this.bundles[assetBundleName] = abInfo;
  431. }
  432. }
  433. else
  434. {
  435. string[] realPath = AssetDatabase.GetAssetPathsFromAssetBundle(assetBundleName);
  436. foreach (string s in realPath)
  437. {
  438. string assetName = Path.GetFileNameWithoutExtension(s);
  439. UnityEngine.Object resource = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(s);
  440. AddResource(assetBundleName, assetName, resource);
  441. }
  442. if (realPath.Length > 0)
  443. {
  444. abInfo = EntityFactory.CreateWithParent<ABInfo, string, AssetBundle>(this, assetBundleName, null);
  445. this.bundles[assetBundleName] = abInfo;
  446. //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
  447. }
  448. else
  449. {
  450. Log.Error("Bundle not exist! BundleName: " + assetBundleName);
  451. }
  452. }
  453. // 编辑器模式也不能同步加载
  454. await TimerComponent.Instance.WaitAsync(20);
  455. #endif
  456. return;
  457. }
  458. p = Path.Combine(PathHelper.AppHotfixResPath, assetBundleName);
  459. if (!File.Exists(p))
  460. {
  461. p = Path.Combine(PathHelper.AppResPath, assetBundleName);
  462. }
  463. if (!File.Exists(p))
  464. {
  465. Log.Error("Async load bundle not exist! BundleName : " + p);
  466. return;
  467. }
  468. using (AssetsBundleLoaderAsync assetsBundleLoaderAsync = EntityFactory.CreateWithParent<AssetsBundleLoaderAsync>(this))
  469. {
  470. assetBundle = await assetsBundleLoaderAsync.LoadAsync(p);
  471. }
  472. if (assetBundle == null)
  473. {
  474. // 获取资源的时候会抛异常,这个地方不直接抛异常,因为有些地方需要Load之后判断是否Load成功
  475. Log.Warning($"assets bundle not found: {assetBundleName}");
  476. return;
  477. }
  478. if (!assetBundle.isStreamedSceneAssetBundle)
  479. {
  480. // 异步load资源到内存cache住
  481. UnityEngine.Object[] assets;
  482. using (AssetsLoaderAsync assetsLoaderAsync = EntityFactory.CreateWithParent<AssetsLoaderAsync, AssetBundle>(this, assetBundle))
  483. {
  484. assets = await assetsLoaderAsync.LoadAllAssetsAsync();
  485. }
  486. foreach (UnityEngine.Object asset in assets)
  487. {
  488. AddResource(assetBundleName, asset.name, asset);
  489. }
  490. }
  491. abInfo = EntityFactory.CreateWithParent<ABInfo, string, AssetBundle>(this, assetBundleName, assetBundle);
  492. this.bundles[assetBundleName] = abInfo;
  493. //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
  494. }
  495. public string DebugString()
  496. {
  497. StringBuilder sb = new StringBuilder();
  498. foreach (ABInfo abInfo in this.bundles.Values)
  499. {
  500. sb.Append($"{abInfo.Name}:{abInfo.RefCount}\n");
  501. }
  502. return sb.ToString();
  503. }
  504. }
  505. }