import { Asset, assetManager, AssetManager, ImageAsset, Prefab, SpriteFrame } from 'cc'; export enum ResourceScope { App = 'app', Scene = 'scene', View = 'view', } export class ResourceManager { private readonly bundles = new Map(); async loadBundle(name: string): Promise { const cached = this.bundles.get(name) ?? assetManager.getBundle(name); if (cached) { this.bundles.set(name, cached); return cached; } return new Promise((resolve, reject) => { assetManager.loadBundle(name, (error, bundle) => { if (error || !bundle) { reject(error ?? new Error(`Bundle not found: ${name}`)); return; } this.bundles.set(name, bundle); resolve(bundle); }); }); } async load( bundleName: string, path: string, type: new (...args: never[]) => T, ): Promise { const bundle = await this.loadBundle(bundleName); return new Promise((resolve, reject) => { bundle.load(path, type, (error, asset) => { if (error || !asset) { reject(error ?? new Error(`Asset not found: ${bundleName}/${path}`)); return; } resolve(asset as T); }); }); } loadPrefab(bundleName: string, path: string): Promise { return this.load(bundleName, path, Prefab); } releaseBundle(name: string): void { const bundle = this.bundles.get(name); if (!bundle) return; bundle.releaseAll(); assetManager.removeBundle(bundle); this.bundles.delete(name); } async loadRemoteSp(url: string): Promise { const img = await this.loadRemoteRes(url); const sp = SpriteFrame.createWithImage(img); return sp; } async loadRemoteRes(url: string): Promise { return new Promise((resolve, reject) => { assetManager.loadRemote(url, (err, res) => { if (err) { console.error(err, url); resolve(null); return; } resolve(res); }); }) } }