| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- 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<string, AssetManager.Bundle>();
- async loadBundle(name: string): Promise<AssetManager.Bundle> {
- 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<T extends Asset>(
- bundleName: string,
- path: string,
- type: new (...args: never[]) => T,
- ): Promise<T> {
- 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<Prefab> {
- 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<SpriteFrame | null> {
- const img = await this.loadRemoteRes<ImageAsset>(url);
- const sp = SpriteFrame.createWithImage(img);
- return sp;
- }
- async loadRemoteRes<T extends Asset>(url: string): Promise<T | null> {
- return new Promise<T>((resolve, reject) => {
- assetManager.loadRemote<T>(url, (err, res) => {
- if (err) {
- console.error(err, url);
- resolve(null);
- return;
- }
- resolve(res);
- });
- })
- }
- }
|