ResourcesComponent.cs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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 Model
  12. {
  13. public class ABInfo : Disposer
  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. public class ResourcesComponent : Component
  49. {
  50. public static AssetBundleManifest AssetBundleManifestObject { get; set; }
  51. private readonly Dictionary<string, UnityEngine.Object> resourceCache = new Dictionary<string, UnityEngine.Object>();
  52. private readonly Dictionary<string, ABInfo> bundles = new Dictionary<string, ABInfo>();
  53. // lru缓存队列
  54. private readonly QueueDictionary<string, ABInfo> cacheDictionary = new QueueDictionary<string, ABInfo>();
  55. public override void Dispose()
  56. {
  57. if (this.IsDisposed)
  58. {
  59. return;
  60. }
  61. base.Dispose();
  62. foreach (var abInfo in this.bundles)
  63. {
  64. abInfo.Value?.AssetBundle?.Unload(true);
  65. }
  66. this.bundles.Clear();
  67. this.cacheDictionary.Clear();
  68. this.resourceCache.Clear();
  69. }
  70. public K GetAsset<K>(string bundleName, string prefab) where K : class
  71. {
  72. string path = $"{bundleName}/{prefab}".ToLower();
  73. UnityEngine.Object resource = null;
  74. if (!this.resourceCache.TryGetValue(path, out resource))
  75. {
  76. throw new Exception($"not found asset: {path}");
  77. }
  78. K k = resource as K;
  79. if (k == null)
  80. {
  81. throw new Exception($"asset type error, type: {k.GetType().Name}, path: {path}");
  82. }
  83. return k;
  84. }
  85. public void UnloadBundle(string assetBundleName)
  86. {
  87. assetBundleName = assetBundleName.ToLower();
  88. string[] dependencies = ResourcesHelper.GetSortedDependencies(assetBundleName);
  89. //Log.Debug($"-----------dep unload {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  90. foreach (string dependency in dependencies)
  91. {
  92. this.UnloadOneBundle(dependency);
  93. }
  94. }
  95. private void UnloadOneBundle(string assetBundleName)
  96. {
  97. assetBundleName = assetBundleName.ToLower();
  98. //Log.Debug($"unload bundle {assetBundleName}");
  99. ABInfo abInfo;
  100. if (!this.bundles.TryGetValue(assetBundleName, out abInfo))
  101. {
  102. throw new Exception($"not found assetBundle: {assetBundleName}");
  103. }
  104. --abInfo.RefCount;
  105. if (abInfo.RefCount > 0)
  106. {
  107. return;
  108. }
  109. this.bundles.Remove(assetBundleName);
  110. // 缓存10个包
  111. this.cacheDictionary.Enqueue(assetBundleName, abInfo);
  112. if (this.cacheDictionary.Count > 10)
  113. {
  114. abInfo = this.cacheDictionary[this.cacheDictionary.FirstKey];
  115. this.cacheDictionary.Dequeue();
  116. abInfo.Dispose();
  117. }
  118. //Log.Debug($"cache count: {this.cacheDictionary.Count}");
  119. }
  120. /// <summary>
  121. /// 同步加载assetbundle
  122. /// </summary>
  123. /// <param name="assetBundleName"></param>
  124. /// <returns></returns>
  125. public void LoadBundle(string assetBundleName)
  126. {
  127. assetBundleName = assetBundleName.ToLower();
  128. string[] dependencies = ResourcesHelper.GetSortedDependencies(assetBundleName);
  129. Log.Debug($"-----------dep load {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  130. foreach (string dependency in dependencies)
  131. {
  132. if (string.IsNullOrEmpty(dependency))
  133. {
  134. continue;
  135. }
  136. this.LoadOneBundle(dependency);
  137. }
  138. }
  139. public void LoadOneBundle(string assetBundleName)
  140. {
  141. ABInfo abInfo;
  142. if (this.bundles.TryGetValue(assetBundleName, out abInfo))
  143. {
  144. ++abInfo.RefCount;
  145. return;
  146. }
  147. if (this.cacheDictionary.ContainsKey(assetBundleName))
  148. {
  149. abInfo = this.cacheDictionary[assetBundleName];
  150. ++abInfo.RefCount;
  151. this.bundles[assetBundleName] = abInfo;
  152. this.cacheDictionary.Remove(assetBundleName);
  153. return;
  154. }
  155. if (!Define.IsAsync)
  156. {
  157. #if UNITY_EDITOR
  158. string[] realPath = AssetDatabase.GetAssetPathsFromAssetBundle(assetBundleName);
  159. foreach (string s in realPath)
  160. {
  161. string assetName = Path.GetFileNameWithoutExtension(s);
  162. string path = $"{assetBundleName}/{assetName}".ToLower();
  163. UnityEngine.Object resource = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(s);
  164. this.resourceCache[path] = resource;
  165. }
  166. this.bundles[assetBundleName] = new ABInfo(assetBundleName, null);
  167. return;
  168. #endif
  169. }
  170. AssetBundle assetBundle = AssetBundle.LoadFromFile(Path.Combine(PathHelper.AppHotfixResPath, assetBundleName));
  171. if (!assetBundle.isStreamedSceneAssetBundle)
  172. {
  173. // 异步load资源到内存cache住
  174. UnityEngine.Object[] assets = assetBundle.LoadAllAssets();
  175. foreach (UnityEngine.Object asset in assets)
  176. {
  177. string path = $"{assetBundleName}/{asset.name}".ToLower();
  178. this.resourceCache[path] = asset;
  179. }
  180. }
  181. this.bundles[assetBundleName] = new ABInfo(assetBundleName, assetBundle);
  182. }
  183. /// <summary>
  184. /// 异步加载assetbundle
  185. /// </summary>
  186. /// <param name="assetBundleName"></param>
  187. /// <returns></returns>
  188. public async Task LoadBundleAsync(string assetBundleName)
  189. {
  190. assetBundleName = assetBundleName.ToLower();
  191. string[] dependencies = ResourcesHelper.GetSortedDependencies(assetBundleName);
  192. //Log.Debug($"-----------dep load {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  193. foreach (string dependency in dependencies)
  194. {
  195. if (string.IsNullOrEmpty(dependency))
  196. {
  197. continue;
  198. }
  199. await this.LoadOneBundleAsync(dependency);
  200. }
  201. }
  202. public async Task LoadOneBundleAsync(string assetBundleName)
  203. {
  204. ABInfo abInfo;
  205. if (this.bundles.TryGetValue(assetBundleName, out abInfo))
  206. {
  207. ++abInfo.RefCount;
  208. return;
  209. }
  210. if (this.cacheDictionary.ContainsKey(assetBundleName))
  211. {
  212. abInfo = this.cacheDictionary[assetBundleName];
  213. ++abInfo.RefCount;
  214. this.bundles[assetBundleName] = abInfo;
  215. this.cacheDictionary.Remove(assetBundleName);
  216. return;
  217. }
  218. if (!Define.IsAsync)
  219. {
  220. #if UNITY_EDITOR
  221. string[] realPath = AssetDatabase.GetAssetPathsFromAssetBundle(assetBundleName);
  222. foreach (string s in realPath)
  223. {
  224. string assetName = Path.GetFileNameWithoutExtension(s);
  225. string path = $"{assetBundleName}/{assetName}".ToLower();
  226. UnityEngine.Object resource = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(s);
  227. this.resourceCache[path] = resource;
  228. }
  229. this.bundles[assetBundleName] = new ABInfo(assetBundleName, null);
  230. return;
  231. #endif
  232. }
  233. AssetBundle assetBundle;
  234. using (AssetsBundleLoaderAsync assetsBundleLoaderAsync = ComponentFactory.Create<AssetsBundleLoaderAsync>())
  235. {
  236. assetBundle = await assetsBundleLoaderAsync.LoadAsync(assetBundleName);
  237. }
  238. if (!assetBundle.isStreamedSceneAssetBundle)
  239. {
  240. // 异步load资源到内存cache住
  241. UnityEngine.Object[] assets;
  242. using (AssetsLoaderAsync assetsLoaderAsync = ComponentFactory.Create<AssetsLoaderAsync, AssetBundle>(assetBundle))
  243. {
  244. assets = await assetsLoaderAsync.LoadAllAssetsAsync();
  245. }
  246. foreach (UnityEngine.Object asset in assets)
  247. {
  248. string path = $"{assetBundleName}/{asset.name}".ToLower();
  249. this.resourceCache[path] = asset;
  250. }
  251. }
  252. this.bundles[assetBundleName] = new ABInfo(assetBundleName, assetBundle);
  253. }
  254. public string DebugString()
  255. {
  256. StringBuilder sb = new StringBuilder();
  257. foreach (ABInfo abInfo in this.bundles.Values)
  258. {
  259. sb.Append($"{abInfo.Name}:{abInfo.RefCount}\n");
  260. }
  261. return sb.ToString();
  262. }
  263. }
  264. }