import { Texture2D, AudioClip, Asset, SpriteFrame, assetManager } from "cc"; /**图片内存 */ export default class ResourceMemoryChecker { static check = {}; // 纹理资源计算(含SpriteFrame) static getTextureMemory(texture: Texture2D): number { if(this.check[texture.uuid]){return 0;} this.check[texture.uuid] = 1; const formatSizeMap = { [Texture2D.PixelFormat.RGBA8888]: 4, [Texture2D.PixelFormat.RGB888]: 3, [Texture2D.PixelFormat.RGBA4444]: 2, // 扩展其他格式... }; if(!formatSizeMap[texture.getPixelFormat()]){ ConsoleEx.Log(texture.getPixelFormat()) } const bpp = formatSizeMap[texture.getPixelFormat()] || 4; return texture.width * texture.height * bpp; } // 音频资源计算(单位:字节) static getAudioMemory(clip: AudioClip): number { //@ts-ignore return clip['_file']?.size || clip.sampleCount * clip.channelCount * 2; } // 统一测量入口 static getMemoryUsage(asset: Asset): number { if (asset instanceof Texture2D) return this.getTextureMemory(asset); //@ts-ignore if (asset instanceof SpriteFrame) return this.getTextureMemory(asset.texture); if (asset instanceof AudioClip) return this.getAudioMemory(asset); // 其他资源类型可扩展 return 0; } static generateMemoryReport(): { totalKB: number, totalMB:number, details: { uuid: string, type: string, sizeKB: number,sizeMB:number }[] } { const details = []; let totalBytes = 0; this.check = {}; //const loadedAssets = Array.from(assetManager.assets.values()); assetManager.assets.forEach(asset => { const bytes = this.getMemoryUsage(asset); const uuid = asset.uuid; if (bytes > 0) { totalBytes += bytes; details.push({ uuid, type: asset.constructor.name, sizeKB: parseFloat((bytes / 1024).toFixed(2)), sizeMB: parseFloat((bytes / 1024 /1024) .toFixed(2)) }); } }); details.sort((a,b)=>{ return b.sizeKB - a.sizeKB; }) return { totalKB: parseFloat((totalBytes / 1024).toFixed(2)), totalMB: parseFloat((totalBytes / 1024/ 1024).toFixed(2)) , details }; } } window["ResourceMemoryChecker"] = ResourceMemoryChecker;