ResBaseAsset.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import AssetsBundleMgr from "../../utils/AssetsBundleMgr";
  2. const { ccclass, disallowMultiple } = cc._decorator;
  3. export enum EResType {
  4. UI,
  5. Prefab /** 直接加载预制的形式 */,
  6. SpriteFrame,
  7. SpriteAtlas,
  8. Spine,
  9. DragonBones,
  10. Texture2D,
  11. ImageAsset,
  12. Material,
  13. Audio,
  14. TTFFont /** TTF 字体 */,
  15. Text /** Txt 文件 */,
  16. ParticleAsset /** 粒子资源 */,
  17. FntFont /** Fnt 字体 */,
  18. Json,
  19. }
  20. /**
  21. * 精灵组件,自动管理资源的引用计数
  22. */
  23. @ccclass
  24. @disallowMultiple
  25. export abstract class ResBaseAsset<T extends cc.Asset> extends cc.Component {
  26. // 动态加载的资源
  27. private m_Asset: T = undefined;
  28. private m_AssetUrl: string = undefined;
  29. get Asset(): T {
  30. return this.m_Asset;
  31. }
  32. protected onEnable(): void { }
  33. /**
  34. * 加载 url 资源,只会回调最后一次加载
  35. * @param bundle
  36. * @param url
  37. * @param cb
  38. * @returns
  39. */
  40. protected async loadAsset(bundle: string, url: string, type: any, cb?: (asset: T) => void) {
  41. let that = this;
  42. AssetsBundleMgr.loadBundle(bundle, (err, bundle) => {
  43. if (err) {
  44. console.log("SpineNode:bundle load failed:", url, err);
  45. cb(null);
  46. return;
  47. }
  48. let cacheAsset: T = bundle.get(url, type);
  49. if (cacheAsset) {
  50. if (that.m_Asset) {
  51. this.addDelayRelease(that.m_Asset);
  52. }
  53. cacheAsset.addRef();
  54. that.m_Asset = cacheAsset;
  55. cb(cacheAsset);
  56. } else {
  57. bundle.load(url, type, (err: Error, asset: T) => {
  58. if (err) {
  59. console.warn("asset not found:", url, err.message);
  60. cb(null);
  61. return;
  62. }
  63. if (that.m_Asset) {
  64. // that.m_Asset.decRef();
  65. this.addDelayRelease(that.m_Asset);
  66. }
  67. asset.addRef();
  68. that.m_Asset = asset;
  69. cb(asset);
  70. });
  71. }
  72. });
  73. }
  74. /**
  75. * 重置资源
  76. */
  77. public resetRes(): void {
  78. if (this.m_Asset) {
  79. // this.m_Asset.decRef();
  80. this.addDelayRelease(this.m_Asset);
  81. this.m_Asset = null;
  82. this.m_AssetUrl = null;
  83. }
  84. }
  85. protected onDestroy(): void {
  86. this.resetRes();
  87. }
  88. /** 10秒延迟释放资源 */
  89. protected addDelayRelease(asset: cc.Asset) {
  90. setTimeout(() => {
  91. asset.decRef();
  92. }, 30000);
  93. }
  94. }