ResourceManager.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import { Asset, assetManager, AssetManager, ImageAsset, Prefab, SpriteFrame } from 'cc';
  2. export enum ResourceScope {
  3. App = 'app',
  4. Scene = 'scene',
  5. View = 'view',
  6. }
  7. export class ResourceManager {
  8. private readonly bundles = new Map<string, AssetManager.Bundle>();
  9. async loadBundle(name: string): Promise<AssetManager.Bundle> {
  10. const cached = this.bundles.get(name) ?? assetManager.getBundle(name);
  11. if (cached) {
  12. this.bundles.set(name, cached);
  13. return cached;
  14. }
  15. return new Promise((resolve, reject) => {
  16. assetManager.loadBundle(name, (error, bundle) => {
  17. if (error || !bundle) {
  18. reject(error ?? new Error(`Bundle not found: ${name}`));
  19. return;
  20. }
  21. this.bundles.set(name, bundle);
  22. resolve(bundle);
  23. });
  24. });
  25. }
  26. async load<T extends Asset>(
  27. bundleName: string,
  28. path: string,
  29. type: new (...args: never[]) => T,
  30. ): Promise<T> {
  31. const bundle = await this.loadBundle(bundleName);
  32. return new Promise((resolve, reject) => {
  33. bundle.load(path, type, (error, asset) => {
  34. if (error || !asset) {
  35. reject(error ?? new Error(`Asset not found: ${bundleName}/${path}`));
  36. return;
  37. }
  38. resolve(asset as T);
  39. });
  40. });
  41. }
  42. loadPrefab(bundleName: string, path: string): Promise<Prefab> {
  43. return this.load(bundleName, path, Prefab);
  44. }
  45. releaseBundle(name: string): void {
  46. const bundle = this.bundles.get(name);
  47. if (!bundle) return;
  48. bundle.releaseAll();
  49. assetManager.removeBundle(bundle);
  50. this.bundles.delete(name);
  51. }
  52. async loadRemoteSp(url: string): Promise<SpriteFrame | null> {
  53. const img = await this.loadRemoteRes<ImageAsset>(url);
  54. const sp = SpriteFrame.createWithImage(img);
  55. return sp;
  56. }
  57. async loadRemoteRes<T extends Asset>(url: string): Promise<T | null> {
  58. return new Promise<T>((resolve, reject) => {
  59. assetManager.loadRemote<T>(url, (err, res) => {
  60. if (err) {
  61. console.error(err, url);
  62. resolve(null);
  63. return;
  64. }
  65. resolve(res);
  66. });
  67. })
  68. }
  69. }