ResourcesComponent.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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. public class ABInfo : Entity
  23. {
  24. public string Name { get; set; }
  25. public int RefCount { get; set; }
  26. public AssetBundle AssetBundle;
  27. public override void Dispose()
  28. {
  29. if (this.IsDisposed)
  30. {
  31. return;
  32. }
  33. base.Dispose();
  34. //Log.Debug($"desdroy assetbundle: {this.Name}");
  35. if (this.AssetBundle != null)
  36. {
  37. this.AssetBundle.Unload(true);
  38. }
  39. this.RefCount = 0;
  40. this.Name = "";
  41. }
  42. }
  43. // 用于字符串转换,减少GC
  44. public static class AssetBundleHelper
  45. {
  46. public static readonly Dictionary<int, string> IntToStringDict = new Dictionary<int, string>();
  47. public static readonly Dictionary<string, string> StringToABDict = new Dictionary<string, string>();
  48. public static readonly Dictionary<string, string> BundleNameToLowerDict = new Dictionary<string, string>()
  49. {
  50. { "StreamingAssets", "StreamingAssets" }
  51. };
  52. // 缓存包依赖,不用每次计算
  53. public static Dictionary<string, string[]> DependenciesCache = new Dictionary<string, string[]>();
  54. public static string IntToString(this int value)
  55. {
  56. string result;
  57. if (IntToStringDict.TryGetValue(value, out result))
  58. {
  59. return result;
  60. }
  61. result = value.ToString();
  62. IntToStringDict[value] = result;
  63. return result;
  64. }
  65. public static string StringToAB(this string value)
  66. {
  67. string result;
  68. if (StringToABDict.TryGetValue(value, out result))
  69. {
  70. return result;
  71. }
  72. result = value + ".unity3d";
  73. StringToABDict[value] = result;
  74. return result;
  75. }
  76. public static string IntToAB(this int value)
  77. {
  78. return value.IntToString().StringToAB();
  79. }
  80. public static string BundleNameToLower(this string value)
  81. {
  82. string result;
  83. if (BundleNameToLowerDict.TryGetValue(value, out result))
  84. {
  85. return result;
  86. }
  87. result = value.ToLower();
  88. BundleNameToLowerDict[value] = result;
  89. return result;
  90. }
  91. public static string[] GetDependencies(string assetBundleName)
  92. {
  93. string[] dependencies = new string[0];
  94. if (DependenciesCache.TryGetValue(assetBundleName,out dependencies))
  95. {
  96. return dependencies;
  97. }
  98. if (!Define.IsAsync)
  99. {
  100. #if UNITY_EDITOR
  101. dependencies = AssetDatabase.GetAssetBundleDependencies(assetBundleName, true);
  102. #endif
  103. }
  104. else
  105. {
  106. dependencies = ResourcesComponent.AssetBundleManifestObject.GetAllDependencies(assetBundleName);
  107. }
  108. DependenciesCache.Add(assetBundleName, dependencies);
  109. return dependencies;
  110. }
  111. public static string[] GetSortedDependencies(string assetBundleName)
  112. {
  113. Dictionary<string, int> info = new Dictionary<string, int>();
  114. List<string> parents = new List<string>();
  115. CollectDependencies(parents, assetBundleName, info);
  116. string[] ss = info.OrderBy(x => x.Value).Select(x => x.Key).ToArray();
  117. return ss;
  118. }
  119. public static void CollectDependencies(List<string> parents, string assetBundleName, Dictionary<string, int> info)
  120. {
  121. parents.Add(assetBundleName);
  122. string[] deps = GetDependencies(assetBundleName);
  123. foreach (string parent in parents)
  124. {
  125. if (!info.ContainsKey(parent))
  126. {
  127. info[parent] = 0;
  128. }
  129. info[parent] += deps.Length;
  130. }
  131. foreach (string dep in deps)
  132. {
  133. if (parents.Contains(dep))
  134. {
  135. throw new Exception($"包有循环依赖,请重新标记: {assetBundleName} {dep}");
  136. }
  137. CollectDependencies(parents, dep, info);
  138. }
  139. parents.RemoveAt(parents.Count - 1);
  140. }
  141. }
  142. public class ResourcesComponent : Entity
  143. {
  144. public static AssetBundleManifest AssetBundleManifestObject { get; set; }
  145. private readonly Dictionary<string, Dictionary<string, UnityEngine.Object>> resourceCache = new Dictionary<string, Dictionary<string, UnityEngine.Object>>();
  146. private readonly Dictionary<string, ABInfo> bundles = new Dictionary<string, ABInfo>();
  147. public override void Dispose()
  148. {
  149. if (this.IsDisposed)
  150. {
  151. return;
  152. }
  153. base.Dispose();
  154. foreach (var abInfo in this.bundles)
  155. {
  156. abInfo.Value.Dispose();
  157. }
  158. this.bundles.Clear();
  159. this.resourceCache.Clear();
  160. }
  161. public UnityEngine.Object GetAsset(string bundleName, string prefab)
  162. {
  163. Dictionary<string, UnityEngine.Object> dict;
  164. if (!this.resourceCache.TryGetValue(bundleName.BundleNameToLower(), out dict))
  165. {
  166. throw new Exception($"not found asset: {bundleName} {prefab}");
  167. }
  168. UnityEngine.Object resource = null;
  169. if (!dict.TryGetValue(prefab, out resource))
  170. {
  171. throw new Exception($"not found asset: {bundleName} {prefab}");
  172. }
  173. return resource;
  174. }
  175. public void UnloadBundle(string assetBundleName)
  176. {
  177. assetBundleName = assetBundleName.BundleNameToLower();
  178. string[] dependencies = AssetBundleHelper.GetSortedDependencies(assetBundleName);
  179. //Log.Debug($"-----------dep unload {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  180. foreach (string dependency in dependencies)
  181. {
  182. this.UnloadOneBundle(dependency);
  183. }
  184. }
  185. private void UnloadOneBundle(string assetBundleName)
  186. {
  187. assetBundleName = assetBundleName.BundleNameToLower();
  188. ABInfo abInfo;
  189. if (!this.bundles.TryGetValue(assetBundleName, out abInfo))
  190. {
  191. throw new Exception($"not found assetBundle: {assetBundleName}");
  192. }
  193. //Log.Debug($"---------- unload one bundle {assetBundleName} refcount: {abInfo.RefCount - 1}");
  194. --abInfo.RefCount;
  195. if (abInfo.RefCount > 0)
  196. {
  197. return;
  198. }
  199. this.bundles.Remove(assetBundleName);
  200. this.resourceCache.Remove(assetBundleName);
  201. abInfo.Dispose();
  202. //Log.Debug($"cache count: {this.cacheDictionary.Count}");
  203. }
  204. /// <summary>
  205. /// 同步加载assetbundle
  206. /// </summary>
  207. /// <param name="assetBundleName"></param>
  208. /// <returns></returns>
  209. public void LoadBundle(string assetBundleName)
  210. {
  211. assetBundleName = assetBundleName.ToLower();
  212. string[] dependencies = AssetBundleHelper.GetSortedDependencies(assetBundleName);
  213. //Log.Debug($"-----------dep load {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  214. foreach (string dependency in dependencies)
  215. {
  216. if (string.IsNullOrEmpty(dependency))
  217. {
  218. continue;
  219. }
  220. this.LoadOneBundle(dependency);
  221. }
  222. }
  223. public void AddResource(string bundleName, string assetName, UnityEngine.Object resource)
  224. {
  225. Dictionary<string, UnityEngine.Object> dict;
  226. if (!this.resourceCache.TryGetValue(bundleName.BundleNameToLower(), out dict))
  227. {
  228. dict = new Dictionary<string, UnityEngine.Object>();
  229. this.resourceCache[bundleName] = dict;
  230. }
  231. dict[assetName] = resource;
  232. }
  233. public void LoadOneBundle(string assetBundleName)
  234. {
  235. //Log.Debug($"---------------load one bundle {assetBundleName}");
  236. ABInfo abInfo;
  237. if (this.bundles.TryGetValue(assetBundleName, out abInfo))
  238. {
  239. ++abInfo.RefCount;
  240. return;
  241. }
  242. if (!Define.IsAsync)
  243. {
  244. string[] realPath = null;
  245. #if UNITY_EDITOR
  246. realPath = AssetDatabase.GetAssetPathsFromAssetBundle(assetBundleName);
  247. foreach (string s in realPath)
  248. {
  249. string assetName = Path.GetFileNameWithoutExtension(s);
  250. UnityEngine.Object resource = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(s);
  251. AddResource(assetBundleName, assetName, resource);
  252. }
  253. abInfo = EntityFactory.CreateWithParent<ABInfo, string, AssetBundle>(this, assetBundleName, null);
  254. this.bundles[assetBundleName] = abInfo;
  255. #endif
  256. return;
  257. }
  258. string p = Path.Combine(PathHelper.AppHotfixResPath, assetBundleName);
  259. AssetBundle assetBundle = null;
  260. if (File.Exists(p))
  261. {
  262. assetBundle = AssetBundle.LoadFromFile(p);
  263. }
  264. else
  265. {
  266. p = Path.Combine(PathHelper.AppResPath, assetBundleName);
  267. assetBundle = AssetBundle.LoadFromFile(p);
  268. }
  269. if (assetBundle == null)
  270. {
  271. throw new Exception($"assets bundle not found: {assetBundleName}");
  272. }
  273. if (!assetBundle.isStreamedSceneAssetBundle)
  274. {
  275. // 异步load资源到内存cache住
  276. UnityEngine.Object[] assets = assetBundle.LoadAllAssets();
  277. foreach (UnityEngine.Object asset in assets)
  278. {
  279. AddResource(assetBundleName, asset.name, asset);
  280. }
  281. }
  282. abInfo = EntityFactory.CreateWithParent<ABInfo, string, AssetBundle>(this, assetBundleName, assetBundle);
  283. this.bundles[assetBundleName] = abInfo;
  284. }
  285. /// <summary>
  286. /// 异步加载assetbundle
  287. /// </summary>
  288. /// <param name="assetBundleName"></param>
  289. /// <returns></returns>
  290. public async ETTask LoadBundleAsync(string assetBundleName)
  291. {
  292. assetBundleName = assetBundleName.ToLower();
  293. string[] dependencies = AssetBundleHelper.GetSortedDependencies(assetBundleName);
  294. // Log.Debug($"-----------dep load {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  295. foreach (string dependency in dependencies)
  296. {
  297. if (string.IsNullOrEmpty(dependency))
  298. {
  299. continue;
  300. }
  301. await this.LoadOneBundleAsync(dependency);
  302. }
  303. }
  304. public async ETTask LoadOneBundleAsync(string assetBundleName)
  305. {
  306. ABInfo abInfo;
  307. if (this.bundles.TryGetValue(assetBundleName, out abInfo))
  308. {
  309. ++abInfo.RefCount;
  310. return;
  311. }
  312. //Log.Debug($"---------------load one bundle {assetBundleName}");
  313. if (!Define.IsAsync)
  314. {
  315. string[] realPath = null;
  316. #if UNITY_EDITOR
  317. realPath = AssetDatabase.GetAssetPathsFromAssetBundle(assetBundleName);
  318. foreach (string s in realPath)
  319. {
  320. string assetName = Path.GetFileNameWithoutExtension(s);
  321. UnityEngine.Object resource = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(s);
  322. AddResource(assetBundleName, assetName, resource);
  323. }
  324. abInfo = EntityFactory.CreateWithParent<ABInfo, string, AssetBundle>(this, assetBundleName, null);
  325. this.bundles[assetBundleName] = abInfo;
  326. #endif
  327. return;
  328. }
  329. string p = Path.Combine(PathHelper.AppHotfixResPath, assetBundleName);
  330. AssetBundle assetBundle = null;
  331. if (!File.Exists(p))
  332. {
  333. p = Path.Combine(PathHelper.AppResPath, assetBundleName);
  334. }
  335. using (AssetsBundleLoaderAsync assetsBundleLoaderAsync = EntityFactory.Create<AssetsBundleLoaderAsync>(this.Domain))
  336. {
  337. assetBundle = await assetsBundleLoaderAsync.LoadAsync(p);
  338. }
  339. if (assetBundle == null)
  340. {
  341. throw new Exception($"assets bundle not found: {assetBundleName}");
  342. }
  343. if (!assetBundle.isStreamedSceneAssetBundle)
  344. {
  345. // 异步load资源到内存cache住
  346. UnityEngine.Object[] assets;
  347. using (AssetsLoaderAsync assetsLoaderAsync = EntityFactory.Create<AssetsLoaderAsync, AssetBundle>(this.Domain, assetBundle))
  348. {
  349. assets = await assetsLoaderAsync.LoadAllAssetsAsync();
  350. }
  351. foreach (UnityEngine.Object asset in assets)
  352. {
  353. AddResource(assetBundleName, asset.name, asset);
  354. }
  355. }
  356. abInfo = EntityFactory.CreateWithParent<ABInfo, string, AssetBundle>(this, assetBundleName, assetBundle);
  357. this.bundles[assetBundleName] = abInfo;
  358. }
  359. public string DebugString()
  360. {
  361. StringBuilder sb = new StringBuilder();
  362. foreach (ABInfo abInfo in this.bundles.Values)
  363. {
  364. sb.Append($"{abInfo.Name}:{abInfo.RefCount}\n");
  365. }
  366. return sb.ToString();
  367. }
  368. }
  369. }