ResourcesComponent.cs 11 KB

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