Asset.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using Object = UnityEngine.Object;
  5. namespace VEngine
  6. {
  7. public class Asset : Loadable, IEnumerator
  8. {
  9. public static readonly Dictionary<string, Asset> Cache = new Dictionary<string, Asset>();
  10. public static readonly Dictionary<string, int> CacheCount = new Dictionary<string, int>();
  11. public static readonly List<Asset> Unused = new List<Asset>();
  12. public Action<Asset> completed;
  13. public Object asset { get; protected set; }
  14. protected Type type { get; set; }
  15. public bool MoveNext()
  16. {
  17. return !isDone;
  18. }
  19. public void Reset()
  20. {
  21. }
  22. protected void OnLoaded(Object target)
  23. {
  24. asset = target;
  25. Finish(asset == null ? "asset == null" : null);
  26. }
  27. public object Current => null;
  28. public T Get<T>() where T : Object
  29. {
  30. return asset as T;
  31. }
  32. protected override void OnComplete()
  33. {
  34. if (completed == null) return;
  35. var saved = completed;
  36. if (completed != null) completed(this);
  37. completed -= saved;
  38. }
  39. protected override void OnUnused()
  40. {
  41. completed = null;
  42. Unused.Add(this);
  43. }
  44. public static Asset LoadAsync(string path, Type type, Action<Asset> completed = null)
  45. {
  46. return LoadInternal(path, type, false, completed);
  47. }
  48. public static Asset Load(string path, Type type)
  49. {
  50. return LoadInternal(path, type, true);
  51. }
  52. internal static Asset LoadInternal(string path, Type type, bool mustCompleteOnNextFrame,
  53. Action<Asset> completed = null)
  54. {
  55. if (!Versions.Contains(path))
  56. {
  57. Logger.W("请添加资源 {0}", path);
  58. return null;
  59. }
  60. if (!Cache.TryGetValue(path, out var item))
  61. {
  62. item = Versions.CreateAsset(path, type);
  63. Cache.Add(path, item);
  64. }
  65. // if (CacheCount.ContainsKey(path))
  66. // {
  67. // CacheCount[path] = CacheCount[path] + 1;
  68. // }
  69. // else
  70. // {
  71. // CacheCount.Add(path, 1);
  72. // }
  73. if (completed != null) item.completed += completed;
  74. item.mustCompleteOnNextFrame = mustCompleteOnNextFrame;
  75. item.Load();
  76. if (mustCompleteOnNextFrame) item.LoadImmediate();
  77. return item;
  78. }
  79. public static void UpdateAssets()
  80. {
  81. for (var index = 0; index < Unused.Count; index++)
  82. {
  83. var item = Unused[index];
  84. if (!item.isDone) continue;
  85. Unused.RemoveAt(index);
  86. index--;
  87. if (!item.reference.unused) continue;
  88. item.Unload();
  89. Cache.Remove(item.pathOrURL);
  90. }
  91. }
  92. }
  93. }