Asset.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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 List<Asset> Unused = new List<Asset>();
  11. public Action<Asset> completed;
  12. public Object asset { get; protected set; }
  13. protected Type type { get; set; }
  14. public bool MoveNext()
  15. {
  16. return !isDone;
  17. }
  18. public void Reset()
  19. {
  20. }
  21. protected void OnLoaded(Object target)
  22. {
  23. asset = target;
  24. Finish(asset == null ? "asset == null" : null);
  25. }
  26. public object Current => null;
  27. public T Get<T>() where T : Object
  28. {
  29. return asset as T;
  30. }
  31. protected override void OnComplete()
  32. {
  33. if (completed == null) return;
  34. var saved = completed;
  35. if (completed != null) completed(this);
  36. completed -= saved;
  37. }
  38. protected override void OnUnused()
  39. {
  40. completed = null;
  41. Unused.Add(this);
  42. }
  43. public static Asset LoadAsync(string path, Type type, Action<Asset> completed = null)
  44. {
  45. return LoadInternal(path, type, false, completed);
  46. }
  47. public static Asset Load(string path, Type type)
  48. {
  49. return LoadInternal(path, type, true);
  50. }
  51. internal static Asset LoadInternal(string path, Type type, bool mustCompleteOnNextFrame,
  52. Action<Asset> completed = null)
  53. {
  54. if (!Versions.Contains(path))
  55. {
  56. Logger.E("FileNotFoundException {0}", path);
  57. return null;
  58. }
  59. if (!Cache.TryGetValue(path, out var item))
  60. {
  61. item = Versions.CreateAsset(path, type);
  62. Cache.Add(path, item);
  63. }
  64. if (completed != null) item.completed += completed;
  65. item.mustCompleteOnNextFrame = mustCompleteOnNextFrame;
  66. item.Load();
  67. if (mustCompleteOnNextFrame) item.LoadImmediate();
  68. return item;
  69. }
  70. public static void UpdateAssets()
  71. {
  72. for (var index = 0; index < Unused.Count; index++)
  73. {
  74. var item = Unused[index];
  75. if (!item.isDone) continue;
  76. Unused.RemoveAt(index);
  77. index--;
  78. if (!item.reference.unused) continue;
  79. item.Unload();
  80. Cache.Remove(item.pathOrURL);
  81. }
  82. }
  83. }
  84. }