ResourcesComponent.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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. this.bundles[assetBundleName] = new ABInfo(assetBundleName, null);
  258. #endif
  259. return;
  260. }
  261. string p = Path.Combine(PathHelper.AppHotfixResPath, assetBundleName);
  262. AssetBundle assetBundle = null;
  263. if (File.Exists(p))
  264. {
  265. assetBundle = AssetBundle.LoadFromFile(p);
  266. }
  267. else
  268. {
  269. p = Path.Combine(PathHelper.AppResPath, assetBundleName);
  270. assetBundle = AssetBundle.LoadFromFile(p);
  271. }
  272. if (assetBundle == null)
  273. {
  274. throw new Exception($"assets bundle not found: {assetBundleName}");
  275. }
  276. if (!assetBundle.isStreamedSceneAssetBundle)
  277. {
  278. // 异步load资源到内存cache住
  279. UnityEngine.Object[] assets = assetBundle.LoadAllAssets();
  280. foreach (UnityEngine.Object asset in assets)
  281. {
  282. AddResource(assetBundleName, asset.name, asset);
  283. }
  284. }
  285. this.bundles[assetBundleName] = new ABInfo(assetBundleName, assetBundle);
  286. }
  287. /// <summary>
  288. /// 异步加载assetbundle
  289. /// </summary>
  290. /// <param name="assetBundleName"></param>
  291. /// <returns></returns>
  292. public async ETTask LoadBundleAsync(string assetBundleName)
  293. {
  294. assetBundleName = assetBundleName.ToLower();
  295. string[] dependencies = AssetBundleHelper.GetSortedDependencies(assetBundleName);
  296. // Log.Debug($"-----------dep load {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  297. foreach (string dependency in dependencies)
  298. {
  299. if (string.IsNullOrEmpty(dependency))
  300. {
  301. continue;
  302. }
  303. await this.LoadOneBundleAsync(dependency);
  304. }
  305. }
  306. public async ETTask LoadOneBundleAsync(string assetBundleName)
  307. {
  308. ABInfo abInfo;
  309. if (this.bundles.TryGetValue(assetBundleName, out abInfo))
  310. {
  311. ++abInfo.RefCount;
  312. return;
  313. }
  314. //Log.Debug($"---------------load one bundle {assetBundleName}");
  315. if (!Define.IsAsync)
  316. {
  317. string[] realPath = null;
  318. #if UNITY_EDITOR
  319. realPath = AssetDatabase.GetAssetPathsFromAssetBundle(assetBundleName);
  320. foreach (string s in realPath)
  321. {
  322. string assetName = Path.GetFileNameWithoutExtension(s);
  323. UnityEngine.Object resource = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(s);
  324. AddResource(assetBundleName, assetName, resource);
  325. }
  326. this.bundles[assetBundleName] = new ABInfo(assetBundleName, null);
  327. #endif
  328. return;
  329. }
  330. string p = Path.Combine(PathHelper.AppHotfixResPath, assetBundleName);
  331. AssetBundle assetBundle = null;
  332. if (!File.Exists(p))
  333. {
  334. p = Path.Combine(PathHelper.AppResPath, assetBundleName);
  335. }
  336. using (AssetsBundleLoaderAsync assetsBundleLoaderAsync = ComponentFactory.Create<AssetsBundleLoaderAsync>())
  337. {
  338. assetBundle = await assetsBundleLoaderAsync.LoadAsync(p);
  339. }
  340. if (assetBundle == null)
  341. {
  342. throw new Exception($"assets bundle not found: {assetBundleName}");
  343. }
  344. if (!assetBundle.isStreamedSceneAssetBundle)
  345. {
  346. // 异步load资源到内存cache住
  347. UnityEngine.Object[] assets;
  348. using (AssetsLoaderAsync assetsLoaderAsync = ComponentFactory.Create<AssetsLoaderAsync, AssetBundle>(assetBundle))
  349. {
  350. assets = await assetsLoaderAsync.LoadAllAssetsAsync();
  351. }
  352. foreach (UnityEngine.Object asset in assets)
  353. {
  354. AddResource(assetBundleName, asset.name, asset);
  355. }
  356. }
  357. this.bundles[assetBundleName] = new ABInfo(assetBundleName, assetBundle);
  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. }