Bundle.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace VEngine
  5. {
  6. public class Bundle : Loadable
  7. {
  8. public static Func<ManifestBundle, Bundle> customBundleCreator;
  9. public static readonly Dictionary<string, Bundle> Cache = new Dictionary<string, Bundle>();
  10. public static readonly List<Bundle> Unused = new List<Bundle>();
  11. public ManifestBundle info;
  12. public AssetBundle assetBundle { get; protected set; }
  13. protected void OnLoaded(AssetBundle bundle)
  14. {
  15. assetBundle = bundle;
  16. Finish(assetBundle == null ? "assetBundle == null" : null);
  17. }
  18. protected override void OnUnused()
  19. {
  20. Unused.Add(this);
  21. }
  22. internal static Bundle LoadInternal(ManifestBundle bundle, bool mustCompleteOnNextFrame)
  23. {
  24. if (bundle == null) throw new NullReferenceException();
  25. if (!Cache.TryGetValue(bundle.nameWithAppendHash, out var item))
  26. {
  27. var url = Versions.GetBundlePathOrURL(bundle);
  28. if (Application.platform == RuntimePlatform.WebGLPlayer)
  29. {
  30. throw new NotImplementedException("开源版不提供 WebGL 支持");
  31. }
  32. else
  33. {
  34. if (customBundleCreator != null) item = customBundleCreator(bundle);
  35. if (item == null)
  36. {
  37. if (url.StartsWith("http://") || url.StartsWith("https://") || url.StartsWith("ftp://"))
  38. item = new DownloadBundle {pathOrURL = url, info = bundle};
  39. else
  40. item = new LocalBundle {pathOrURL = url, info = bundle};
  41. }
  42. }
  43. Cache.Add(bundle.nameWithAppendHash, item);
  44. }
  45. item.mustCompleteOnNextFrame = mustCompleteOnNextFrame;
  46. item.Load();
  47. if (mustCompleteOnNextFrame) item.LoadImmediate();
  48. return item;
  49. }
  50. internal static void UpdateBundles()
  51. {
  52. for (var index = 0; index < Unused.Count; index++)
  53. {
  54. var item = Unused[index];
  55. if (!item.isDone) continue;
  56. Unused.RemoveAt(index);
  57. index--;
  58. if (!item.reference.unused) continue;
  59. item.Unload();
  60. Cache.Remove(item.info.nameWithAppendHash);
  61. if (Updater.Instance.busy) return;
  62. }
  63. }
  64. protected override void OnUnload()
  65. {
  66. if (assetBundle == null) return;
  67. assetBundle.Unload(true);
  68. assetBundle = null;
  69. }
  70. }
  71. }