ResourcesComponent.cs 11 KB

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