Browse Source

fix: 修复 AssetManager 代码质量问题

master
npmrun 3 weeks ago
parent
commit
940b1d55af
  1. 37
      src/core/AssetManager.ts

37
src/core/AssetManager.ts

@ -5,6 +5,7 @@ class AssetManager {
private referenceCounts: Map<string, number> = new Map();
async init(): Promise<void> {
// 硬编码的 /manifest.json 路径是本应用的固定配置
await Assets.init({ manifest: "/manifest.json" });
logger.debug("AssetManager initialized");
}
@ -12,7 +13,12 @@ class AssetManager {
async loadBundle(
name: string,
onProgress?: (progress: number) => void
): Promise<AssetsBundle> {
): Promise<AssetsBundle | null> {
if (name === "") {
logger.warn("AssetManager: Bundle name cannot be empty string");
return null;
}
// 已经加载过,增加引用计数
if (this.referenceCounts.has(name)) {
const count = this.referenceCounts.get(name)! + 1;
@ -24,12 +30,22 @@ class AssetManager {
// 首次加载
logger.debug(`AssetManager: loading bundle "${name}"`);
const bundle = await Assets.loadBundle(name, onProgress);
this.referenceCounts.set(name, 1);
return bundle;
try {
const bundle = await Assets.loadBundle(name, onProgress);
this.referenceCounts.set(name, 1);
return bundle;
} catch (error) {
logger.error(`AssetManager: Failed to load bundle "${name}":`, error);
return null;
}
}
async unloadBundle(name: string): Promise<void> {
if (name === "") {
logger.warn("AssetManager: Bundle name cannot be empty string");
return;
}
if (!this.referenceCounts.has(name)) {
logger.warn(`AssetManager: unloading unloaded bundle "${name}"`);
return;
@ -48,15 +64,28 @@ class AssetManager {
}
isLoaded(name: string): boolean {
if (name === "") {
logger.warn("AssetManager: Bundle name cannot be empty string");
return false;
}
return this.referenceCounts.has(name) && this.referenceCounts.get(name)! > 0;
}
getRefCount(name: string): number {
if (name === "") {
logger.warn("AssetManager: Bundle name cannot be empty string");
return 0;
}
return this.referenceCounts.get(name) ?? 0;
}
clearAll(): void {
// 注意:此方法只会清除本地引用计数,不会从 Pixi 中卸载资源
// 因为完全卸载资源在实际应用中很少需要,且可能导致正在使用的资源失效
this.referenceCounts.clear();
logger.debug("AssetManager: Reference count map cleared");
}
}

Loading…
Cancel
Save