ResourcesComponent.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. #if UNITY_EDITOR
  5. using UnityEditor;
  6. #endif
  7. namespace Model
  8. {
  9. // 用来实例化资源,暂时直接加载,之后可以预先加载
  10. public class ResourcesComponent: Component
  11. {
  12. public static AssetBundleManifest AssetBundleManifestObject { get; set; }
  13. private readonly Dictionary<string, UnityEngine.Object> resourceCache = new Dictionary<string, UnityEngine.Object>();
  14. private readonly Dictionary<string, AssetBundle> bundleCaches = new Dictionary<string, AssetBundle>();
  15. public K GetUnitRefrenceById<K>(string unitId, EntityType entityType) where K : class
  16. {
  17. string assetBundleName = $"unit/{AssetBundleHelper.GetBundleNameById(unitId, entityType)}";
  18. return GetAsset<K>(assetBundleName, unitId);
  19. }
  20. public K GetReference<K>(string bundle, string prefab, string key) where K : class
  21. {
  22. GameObject gameObject = this.GetAsset<GameObject>(bundle, prefab);
  23. return gameObject.GetComponent<ReferenceCollector>().Get<K>(key);
  24. }
  25. public K GetAsset<K>(string bundleName, string prefab) where K : class
  26. {
  27. string path = $"{bundleName}.unity3d/{prefab}".ToLower();
  28. UnityEngine.Object resource = null;
  29. if (this.resourceCache.TryGetValue(path, out resource))
  30. {
  31. return resource as K;
  32. }
  33. if (Define.LoadResourceType == LoadResourceType.Async)
  34. {
  35. if (!this.bundleCaches.ContainsKey($"{bundleName}.unity3d".ToLower()))
  36. {
  37. return null;
  38. }
  39. throw new ConfigException($"异步加载资源,资源不在resourceCache中: {bundleName} {path}");
  40. }
  41. try
  42. {
  43. #if UNITY_EDITOR
  44. string[] realPath = AssetDatabase.GetAssetPathsFromAssetBundleAndAssetName(bundleName.ToLower() + ".unity3d", prefab);
  45. resource = AssetDatabase.LoadAssetAtPath(realPath[0], typeof (GameObject));
  46. this.resourceCache.Add(path, resource);
  47. #endif
  48. }
  49. catch (Exception e)
  50. {
  51. throw new ConfigException($"加载资源出错,输入路径:{path}", e);
  52. }
  53. return resource as K;
  54. }
  55. public override void Dispose()
  56. {
  57. if (this.Id == 0)
  58. {
  59. return;
  60. }
  61. base.Dispose();
  62. foreach (var assetBundle in bundleCaches)
  63. {
  64. assetBundle.Value?.Unload(true);
  65. }
  66. }
  67. }
  68. }