找物源码导读Cocos Creator 3.8 · assets/scripts
0%
已读 0 / 424
目录— 个文件
目录加载中…
…/core/resource/ResourceManager.ts
1import { Asset, assetManager, SpriteAtlas, SpriteFrame, sys } from 'cc';
2import { frameworkManager } from "../base/FrameworkClassRegistry";
3import { IFrameworkManager } from "../base/IFrameworkManager";
4import { Singleton } from "../base/Singleton";
5// import { BUILD } from 'cc/env';
6import { Framework } from "../../Framework";
7import { SdkChannel } from '../../module/sdk/SdkChannel';
8import { SdkConfig } from '../../module/sdk/SdkConfig';
9import { ResourceInfo } from "./ResourceInfo";
10import { ResourceSettings } from "./ResourceFrameConfig";
11import { ResourceInfoAnalysis } from "./ResourceInfoAnalysis";
12import { AssetType, CompleteCallback, IRemoteOptions, ProgressCallback } from "./ResourceTypeDefine";
13import { ResourceAssetLoader, RetryOptions } from "./loader/ResourceAssetLoader";
14import { ResourceBundleLoader } from "./loader/ResourceBundleLoader";
15
16
17/**
18 * 资源管理器
19 * 加载Bundle包接口暴露
20 * 1.预加载 2.加载进度条 3.资源版本管理 4.热更 及 子游戏热更
21 */
22@frameworkManager()
23export class ResourceManager extends Singleton<ResourceManager> implements IFrameworkManager {
24 Name: string = "ResourceManager";
25
26 // 仅持有项目传入的原对象,不创建或复制项目配置。
27 private config: ResourceSettings | null = null;
28
29 /** 读取同一份配置;启动装配遗漏时直接暴露错误,不提供空配置兜底。 */
30 public get Config(): ResourceSettings {
31 if (!this.config) {
32 throw new Error("[ResourceManager] 请先通过 SetConfig 设置资源配置");
33 }
34 return this.config;
35 }
36
37 /** 入口在编辑器同步前注入,初始化后不允许替换配置对象。 */
38 public SetConfig(config: ResourceSettings): void {
39 if (this.isInitialized) {
40 throw new Error("[ResourceManager] Config 只能在初始化前设置");
41 }
42 this.config = config;
43 }
44
45 //资源信息
46 private resourceInfos: Map<string, ResourceInfo> = new Map();
47
48
49 //Asset 资源加载器
50 private assetLoader: ResourceAssetLoader = new ResourceAssetLoader();
51
52 public get AssetLoader(): ResourceAssetLoader {
53 return this.assetLoader;
54 }
55
56 // bundle资源加载器
57 private bundleLoader: ResourceBundleLoader = new ResourceBundleLoader();
58 // 限定装配发生在初始化前,禁止运行中替换仍有缓存/请求的加载器。
59 private isInitialized: boolean = false;
60
61 public get BundleLoader(): ResourceBundleLoader {
62 return this.bundleLoader;
63 }
64
65 /** 项目入口在 ConfigureResource 阶段选择资源实现;实际 Init 在配置同步后执行。 */
66 public SetBundleLoader(loader: ResourceBundleLoader): void {
67 if (this.isInitialized) {
68 throw new Error("[ResourceManager] BundleLoader 只能在初始化前设置");
69 }
70 this.bundleLoader = loader;
71 }
72
73 public async Init(): Promise<void> {
74 // 初始化边界检查,未注入时不能继续启动资源模块。
75 if (!this.config) {
76 throw new Error("[ResourceManager] 请先通过 SetConfig 设置资源配置");
77 }
78
79 // 配置 Cocos 内置下载器重试参数
80 // downloader.maxRetryCount 默认 3,retryInterval 默认 2000ms
81 // 可根据网络环境调整,如弱网场景增大 maxRetryCount
82 assetManager.downloader.maxRetryCount = 3;
83 assetManager.downloader.retryInterval = 3000;
84 // 专项下载适配由选中的加载器负责,管理器不依赖具体游戏。
85 this.bundleLoader.Init();
86 this.isInitialized = true;
87
88 Framework.Log.Log(this.Name, "Init", "初始化资源管理器完成");
89 }
90
91 DeInit(): void {
92 // 重启时清理包内资源缓存,避免复用已被引擎释放的资源。
93 this.assetLoader.ReleaseAllAsset();
94 this.bundleLoader.DeInit();
95 // 管理器单例跨重启保留;新启动重新装配,不能沿用上一项目的专项实现。
96 this.bundleLoader = new ResourceBundleLoader();
97 this.isInitialized = false;
98 // 配置引用保留给后续退出日志/回调读取;下次入口仍会在同步前注入。
99 }
100
101 Update(deltaTime: number): void {
102 // 驱动 AssetLoader 的每帧更新(用于分帧预加载等任务)
103 if (this.assetLoader) {
104 this.assetLoader.Update(deltaTime);
105 }
106 }
107
108 // ======================================== 资源配置相关========================================
109
110 /**
111 * 加载资源信息
112 * @constructor
113 */
114 public async LoadResourceInfo() {
115 await ResourceInfoAnalysis.AnalysisResourceInfosJSON(this.resourceInfos);
116 }
117
118 /**
119 * 根据资源名称获取资源配置信息
120 * @param assetName
121 * @constructor
122 * @private
123 */
124 public GetResourceInfoByAssetName(assetName: string): ResourceInfo | null {
125 if (this.resourceInfos.has(assetName)) {
126 return this.resourceInfos.get(assetName)!;
127 }
128
129 // 清单未覆盖的资源交给当前加载器解析,管理器不识别项目命名。
130 const bundleMapResourceInfo = this.bundleLoader.ResolveResourceInfoByName(assetName);
131 if (bundleMapResourceInfo) {
132 return bundleMapResourceInfo;
133 }
134
135 Framework.Log.Error(this.Name, "GetResourceInfoByAssetName", `资源配置信息不存在: ${assetName}`);
136 return null;
137 }
138
139
140 /** 打印缓存中所有资源信息 */
141 public Dump() {
142 assetManager.assets.forEach((value: Asset, key: string) => {
143 Framework.Log.Log(this.Name, "Dump", `引用数量:${value.refCount}`, assetManager.assets.get(key));
144 })
145 Framework.Log.Log(this.Name, "Dump", `当前资源总数:${assetManager.assets.count}`);
146 }
147
148 /**
149 * 手动请求 JS 垃圾回收。
150 * GC 可能造成瞬时停顿,只建议在加载界面或调试阶段调用。
151 */
152 public ForceGarbageCollect(): void {
153 const startTime = performance.now();
154 switch (SdkConfig.Channel) {
155 case SdkChannel.Tiktok:
156 tt.triggerGC();
157 break;
158 default:
159 sys.garbageCollect();
160 break;
161 }
162 const cost = performance.now() - startTime;
163
164 Framework.Log.Warn(
165 this.Name,
166 "ForceGarbageCollect",
167 `[GC] 手动 GC 调用完成, 调用耗时: ${cost.toFixed(2)} ms`
168 );
169 }
170
171 // ======================================== 远程资源加载========================================
172
173 private static readonly REMOTE_ERROR_CACHE_TTL_MS = 60 * 1000;
174 private remoteErrorCache: Map<string, { failCount: number; lastFailTime: number }> = new Map();
175
176 /**
177 * 加载远程资源(Cocos downloader 内置重试,默认 maxRetryCount=3, retryInterval=3000ms)
178 * 可通过 assetManager.downloader.maxRetryCount / retryInterval 调整
179 * @param url 资源url
180 * @param options 资源参数,例:{ ext: ".png" }
181 * @example
182 * var opt: IRemoteOptions = { ext: ".png" };
183 * var data = await oops.res.loadRemote<ImageAsset>(this.url, opt);
184 * const texture = new Texture2D();
185 * texture.image = data;
186 *
187 * const spriteFrame = new SpriteFrame();
188 * spriteFrame.texture = texture;
189 *
190 * var sprite = this.sprite.addComponent(Sprite);
191 * sprite.spriteFrame = spriteFrame;
192 */
193 public async LoadRemote<T extends Asset>(opt: {
194 url: string,
195 options: IRemoteOptions | null,
196 MaxRetryCount?: number,
197 RetryInterval?: number,
198 }) {
199 const maxRetry = opt.MaxRetryCount ?? 0;
200 const interval = opt.RetryInterval ?? 0;
201
202 for (let attempt = 0; attempt <= maxRetry; attempt++) {
203 if (attempt > 0) {
204 Framework.Log.Error(this.Name, "LoadRemote", `重试第 ${attempt}/${opt.MaxRetryCount ?? maxRetry} 次加载远程资源: ${opt.url}`);
205 await new Promise<void>(r => setTimeout(r, interval));
206 }
207
208 const data = await new Promise<T | null>((resolve) => {
209 assetManager.loadRemote<T>(opt.url, opt.options, (err, data: T) => {
210 if (err) {
211 Framework.Log.Error(this.Name, "LoadRemote",
212 `第 ${attempt + 1} 次加载远程资源失败: ${opt.url}`,
213 err == null ? "" : typeof err === "object" ? JSON.stringify(err) : String(err));
214 resolve(null);
215 return;
216 }
217 resolve(data);
218 });
219 });
220
221 if (data) {
222 return data;
223 }
224 }
225
226 this.recordRemoteError(opt.url);
227 Framework.Log.Error(this.Name, "LoadRemote", `远程资源加载最终失败(已重试 ${maxRetry} 次): ${opt.url}`);
228 return null;
229 }
230 /** 记录重试错误集 */
231 private recordRemoteError(url: string): void {
232 const entry = this.remoteErrorCache.get(url);
233 if (entry) {
234 entry.failCount++;
235 entry.lastFailTime = Date.now();
236 } else {
237 this.remoteErrorCache.set(url, { failCount: 1, lastFailTime: Date.now() });
238 }
239 this.pruneRemoteErrorCache();
240 }
241
242 private pruneRemoteErrorCache(): void {
243 const now = Date.now();
244 const ttl = ResourceManager.REMOTE_ERROR_CACHE_TTL_MS;
245 for (const [key, entry] of this.remoteErrorCache) {
246 if (now - entry.lastFailTime > ttl) {
247 this.remoteErrorCache.delete(key);
248 }
249 }
250 }
251 /** 重试错误信息构建 */
252 public GetRemoteErrorInfo(url: string): { failCount: number; lastFailTime: number } | null {
253 this.pruneRemoteErrorCache();
254 return this.remoteErrorCache.get(url) ?? null;
255 }
256
257 // ======================================== Bundle资源包管理========================================
258 /**
259 * 加载Bundle包
260 * @constructor
261 */
262 public async LoadBundle(opt: {
263 bundleName: string,
264 options: { [k: string]: any; version?: string; } | null,
265 maxRetryCount?: number,
266 retryInterval?: number,
267 preloadAllBundle?: boolean,
268 }) {
269 // 一次资源加载链路,从 ResourceManager 开始创建 TraceId
270 const traceId = Framework.Log.NextTraceId();
271 const startTime = Date.now();
272 Framework.Log.TraceLog(traceId, this.Name, "LoadBundle", `请求加载 Bundle: ${opt.bundleName}`);
273
274 let bundle = await this.bundleLoader.LoadBundle({
275 bundleName: opt.bundleName,
276 options: opt.options, traceId,
277 maxCount: opt.maxRetryCount,
278 retryTime: opt.retryInterval,
279 preloadAllBundleAssets:
280 opt.preloadAllBundle
281 });
282
283 const cost = Date.now() - startTime;
284 Framework.Log.TraceLog(traceId, this.Name, "LoadBundle", `完成 Bundle 加载: ${opt.bundleName}, 耗时 ${cost} ms`);
285 return bundle;
286 }
287
288 /**
289 * 释放指定 Bundle 及其所有资源
290 * @param bundleName Bundle名称
291 * @constructor
292 */
293 public ReleaseBundle(bundleName: string): void {
294 // 委托 AssetLoader 清理该 Bundle 下的资源缓存
295 this.assetLoader.ReleaseBundleAssets(bundleName, (assetName) => this.GetResourceInfoByAssetName(assetName));
296 this.bundleLoader.ReleaseBundle(bundleName);
297 }
298
299 /**
300 * 释放所有 Bundle 及其关联资源
301 * @constructor
302 */
303 public ReleaseAllBundles(): void {
304 // 调用加载器释放所有 Bundle 实例
305 this.bundleLoader.ReleaseAllBundle();
306
307 // 调用Asset加载器释放所有资源
308 this.assetLoader.ReleaseAllAsset();
309 }
310
311 // ======================================== Asset具体资源管理========================================
312
313 /**
314 * 预加载单个资源(同步回调式)
315 * @param assetName 资源名称
316 * @param type 资源类型
317 * @param onProgress 预加载进度回调(可选)
318 * @param onComplete 预加载完成回调(可选)
319 */
320 public PreLoadAsset<T extends Asset>(assetName: string, type: AssetType<T>, onProgress?: ProgressCallback, onComplete?: CompleteCallback, retryOpts?: RetryOptions
321 ): void {
322 if (!this.resourceInfos.size) {
323 const err = "资源配置信息未加载,无法执行预加载";
324 Framework.Log.Error(this.Name, "PreLoadAsset", err);
325 onComplete?.(new Error(err), null);
326 return;
327 }
328 const traceId = Framework.Log.NextTraceId();
329 Framework.Log.TraceLog(traceId, this.Name, "PreLoadAsset", `开始预加载资源: ${assetName}`);
330 this.assetLoader.PreLoadAsset(assetName, type, onProgress, onComplete, traceId, retryOpts);
331 }
332
333 /**
334 * 预加载单个资源(异步 Promise 式)
335 * @param assetName 资源名称
336 * @param type 资源类型
337 * @returns Promise<T> 预加载完成的资源
338 */
339 public async PreLoadAssetAsync<T extends Asset>(assetName: string, type: AssetType<T>, retryOpts?: RetryOptions): Promise<T> {
340 if (!this.resourceInfos.size) {
341 const err = "资源配置信息未加载,无法执行预加载";
342 Framework.Log.Error(this.Name, "PreLoadAssetAsync", err);
343 return Promise.reject(new Error(err));
344 }
345 const traceId = Framework.Log.NextTraceId();
346 Framework.Log.TraceLog(traceId, this.Name, "PreLoadAssetAsync", `开始预加载资源(Async): ${assetName}`);
347 return this.assetLoader.PreLoadAssetAsync(assetName, type, traceId, retryOpts);
348 }
349
350 /**
351 * 预加载目录资源(同步回调式)
352 * @param bundleName Bundle 名称
353 * @param dirPath 目录路径(Bundle 内相对路径)
354 * @param type 资源类型
355 * @param onProgress 预加载进度回调(可选)
356 * @param onComplete 预加载完成回调(可选)
357 */
358 public PreLoadDir(bundleName: string, dirPath: string, type: AssetType<Asset>, onProgress?: ProgressCallback, onComplete?: CompleteCallback, retryOpts?: RetryOptions): void {
359 const traceId = Framework.Log.NextTraceId();
360 Framework.Log.TraceLog(traceId, this.Name, "PreLoadDir", `开始预加载目录: ${bundleName}/${dirPath}`);
361 this.assetLoader.PreLoadDir(bundleName, dirPath, type, onProgress, onComplete, traceId, retryOpts);
362 }
363
364 /**
365 * 分帧预加载目录资源(按小批次 + 限制并发,缓解卡顿)
366 * @param bundleName Bundle 名称
367 * @param dirPath 目录路径(Bundle 内相对路径)
368 * @param type 资源类型(通常传 Asset)
369 * @param options.batchPerTick 每次定时回调启动的预加载数量(默认 1)
370 * @param options.maxConcurrent 最大同时进行中的预加载数量(默认 2)
371 * @param options.onProgress 进度回调(finished, total)
372 * @param options.onComplete 全部完成时回调
373 */
374 public PreLoadDirByFrames(
375 bundleName: string,
376 dirPath: string,
377 type: AssetType<Asset>,
378 options?: {
379 batchPerTick?: number;
380 maxConcurrent?: number;
381 onProgress?: (finished: number, total: number) => void;
382 onComplete?: () => void;
383 },
384 retryOpts?: RetryOptions,
385 ): void {
386 const traceId = Framework.Log.NextTraceId();
387 Framework.Log.TraceLog(traceId, this.Name, "PreLoadDirByFrames", `开始分帧预加载目录: ${bundleName}/${dirPath}`);
388 const batchPerTick = options?.batchPerTick ?? 1;
389 const maxConcurrent = options?.maxConcurrent ?? 2;
390 this.assetLoader.PreLoadDirByFrames(
391 bundleName,
392 dirPath,
393 type,
394 batchPerTick,
395 maxConcurrent,
396 options?.onProgress,
397 options?.onComplete,
398 traceId,
399 retryOpts,
400 );
401 }
402
403 /**
404 * 加载目录资源(同步回调式)
405 * @param bundleName Bundle 名称
406 * @param dirPath 目录路径(Bundle 内相对路径)
407 * @param type 资源类型
408 * @param onProgress 加载进度回调(可选)
409 * @param onComplete 加载完成回调(可选)
410 */
411 public LoadDir(bundleName: string, dirPath: string, type: AssetType<Asset>, onProgress?: ProgressCallback, onComplete?: CompleteCallback, retryOpts?: RetryOptions): void {
412 const traceId = Framework.Log.NextTraceId();
413 Framework.Log.TraceLog(traceId, this.Name, "LoadDir", `开始加载目录: ${bundleName}/${dirPath}`);
414 this.assetLoader.LoadDir(bundleName, dirPath, type, onProgress, onComplete, traceId, retryOpts);
415 }
416
417 /**
418 * 加载目录资源(异步 Promise 式)
419 * @param bundleName Bundle 名称
420 * @param dirPath 目录路径(Bundle 内相对路径)
421 * @param type 资源类型
422 * @param onProgress 加载进度回调(可选)
423 * @returns Promise<Asset[] | null> 目录下所有资源数组
424 */
425 public LoadDirAsync(bundleName: string, dirPath: string, type: AssetType<Asset>, onProgress?: ProgressCallback, retryOpts?: RetryOptions): Promise<Asset[] | null> {
426 const traceId = Framework.Log.NextTraceId();
427 Framework.Log.TraceLog(traceId, this.Name, "LoadDirAsync", `开始加载目录(Async): ${bundleName}/${dirPath}`);
428 return this.assetLoader.LoadDirAsync(bundleName, dirPath, type, onProgress, traceId, retryOpts);
429 }
430
431 /**
432 * 从指定图集中按名称加载子 SpriteFrame(图集本身会走缓存)
433 * @param atlasAssetName 图集资源名(对应 ResourceInfo.Name)
434 * @param spriteName 图集中子图名称
435 */
436 public async LoadSpriteFrameFromAtlas(atlasAssetName: string, spriteName: string): Promise<SpriteFrame | null> {
437 // // 未打包(编辑器 / 预览 / 浏览器调试等)一律直接按图片名加载,方便开发
438 // if (!BUILD) {
439 // return this.LoadAssetAsync<SpriteFrame>(spriteName, SpriteFrame);
440 // }
441
442 if (this.resourceInfos == null || this.resourceInfos.size <= 0) {
443 const err = "资源配置信息未加载,无法加载图集";
444 Framework.Log.Error(this.Name, "LoadSpriteFrameFromAtlas", err);
445 return null;
446 }
447
448 const traceId = Framework.Log.NextTraceId();
449 Framework.Log.TraceLog(
450 traceId,
451 this.Name,
452 "LoadSpriteFrameFromAtlas",
453 `开始加载图集子图: atlas=${atlasAssetName}, sprite=${spriteName}`
454 );
455
456 // 通过现有 LoadAssetAsync 加载 / 复用图集(内部带有缓存与日志)
457 const atlas = await this.LoadAssetAsync<SpriteAtlas>(atlasAssetName, SpriteAtlas) as SpriteAtlas | null;
458 if (!atlas) {
459 Framework.Log.TraceError(traceId, this.Name, "LoadSpriteFrameFromAtlas", `图集加载失败: ${atlasAssetName}`);
460 return null;
461 }
462
463 const frame = atlas.getSpriteFrame(spriteName);
464 // if (!frame) {
465 // Framework.Log.TraceError(
466 // traceId,
467 // this.Name,
468 // "LoadSpriteFrameFromAtlas",
469 // `图集中不存在子图: ${spriteName}(atlas=${atlasAssetName})`
470 // );
471 // return null;
472 // }
473
474 return frame;
475 }
476
477 /**
478 * 从多张图集中按名称顺序查找子 SpriteFrame:
479 * - 先依次尝试 atlasNames[0..n-1],在任一图集中找到即返回
480 * - 若所有图集都未命中,则退化为直接按贴图名加载 SpriteFrame
481 * - 直接贴图也加载失败时,才认为是“真正缺失”,打出错误日志并返回 null
482 * @param atlasAssetNames 图集资源名数组
483 * @param spriteName 子图名称(通常为 plist 中的 frame 名,去掉 .png)
484 */
485 public async LoadSpriteFrameFromAtlases(atlasAssetNames: string[], spriteName: string): Promise<SpriteFrame | null> {
486 if (!atlasAssetNames || atlasAssetNames.length === 0) {
487 Framework.Log.Error(this.Name, "LoadSpriteFrameFromAtlases", `atlas 列表为空,无法加载子图: ${spriteName}`);
488 return null;
489 }
490
491 // 1. 依次从所有图集中查找子图
492 for (const atlasName of atlasAssetNames) {
493 const frame = await this.LoadSpriteFrameFromAtlas(atlasName, spriteName);
494 if (frame) {
495 return frame;
496 }
497 }
498
499 // 2. 所有图集都没找到,退化为直接按贴图名加载 SpriteFrame(通常对应独立 png)
500 const fallback = await this.LoadAssetAsync<SpriteFrame>(spriteName, SpriteFrame);
501 if (fallback) {
502 Framework.Log.Log(
503 this.Name,
504 "LoadSpriteFrameFromAtlases",
505 `所有图集未命中,已通过贴图名直接加载 SpriteFrame: ${spriteName}`
506 );
507 return fallback;
508 }
509
510 // 3. 图集与独立贴图都加载失败,视为真正缺失
511 Framework.Log.Error(
512 this.Name,
513 "LoadSpriteFrameFromAtlases",
514 `所有图集与贴图都未找到资源: ${spriteName}, atlases=[${atlasAssetNames.join(",")}]`
515 );
516 return null;
517 }
518
519 /**
520 * 加载单个资源(同步回调式)
521 * @param assetName 资源名称
522 * @param type 资源类型
523 * @param onProgress 加载进度回调(可选)
524 * @param onComplete 加载完成回调(可选)
525 */
526 public LoadAsset<T extends Asset>(assetName: string, type: AssetType<T>, onProgress?: ProgressCallback, onComplete?: CompleteCallback, retryOpts?: RetryOptions) {
527 if (this.resourceInfos == null || this.resourceInfos.size <= 0) {
528 Framework.Log.Error(this.Name, "LoadAsset", "资源配置信息未加载成功");
529 return null;
530 }
531 const traceId = Framework.Log.NextTraceId();
532 Framework.Log.TraceLog(traceId, this.Name, "LoadAsset", `开始加载资源: ${assetName}`);
533 return this.assetLoader.LoadAsset(assetName, type, onProgress, onComplete, traceId, retryOpts);
534 }
535
536 /**
537 * 异步加载资源
538 * @param assetName 资源名称
539 * @param type 资源类型
540 * @param onProgress 加载进度回调
541 * @param onComplete 加载完成回调
542 * @constructor
543 */
544 public async LoadAssetAsync<T extends Asset>(assetName: string, type: AssetType<T>, onProgress?: ProgressCallback, onComplete?: CompleteCallback, retryOpts?: RetryOptions): Promise<T | null> {
545 if (this.resourceInfos == null || this.resourceInfos.size <= 0) {
546 Framework.Log.Error(this.Name, "LoadAsset", "资源配置信息未加载成功");
547 return null;
548 }
549
550 const traceId = Framework.Log.NextTraceId();
551 Framework.Log.TraceLog(traceId, this.Name, "LoadAssetAsync", `开始加载资源(Async): ${assetName}`);
552 return this.assetLoader.LoadAssetAsync(assetName, type, onProgress, onComplete, traceId, retryOpts);
553 }
554
555 /**
556 * 释放单个资源
557 * @param assetName 资源名称
558 * @constructor
559 */
560 public ReleaseAsset(assetName: string): void {
561 this.assetLoader.ReleaseAsset(assetName);
562 }
563
564 /**
565 * 清理所有缓存(用于游戏重启或退出)
566 * @private
567 */
568 private ReleaseAllAsset(): void {
569 // 释放所有 Bundle
570 this.bundleLoader.ReleaseAllBundle();
571 // 释放所有资源
572 this.assetLoader.ReleaseAllAsset();
573 }
574}
讲解575 行
资源管理器人工通读

ResourceManager.ts

框架单例与资源总入口,持有项目注入的配置、资源清单和两个加载器,向业务暴露加载、预加载、远程下载与释放接口。Bundle 与 Asset 的实际缓存和重试都下沉到加载器,它只做装配、校验和日志链路。

先看 Config 与 SetConfig 的装配约束,再读 Init 与 DeInit 的生命周期,然后看 Bundle 释放顺序,最后浏览各加载转发方法。

特殊处理与易错点

22注释资源管理器 加载Bundle包接口暴露 1.预加载 2.加载进度条 3.资源版本管理 4.热更 及 子游戏热更
23注释ResourceManager:资源门面:Bundle/Asset/Dir 加载、远程加载重试、图集子图、资源释放、GC 与
24属性名称(string):模块/组件名称,用于日志、缓存 Key 或资源查找。
27属性入口注入的项目资源配置原对象,初始化前写入,之后只读。
30方法返回入口注入的资源配置,未设置时直接抛错,不做默认值兜底。
38方法保存资源配置引用,已初始化后再调用会抛错,禁止运行中替换。
46属性资源名到 ResourceInfo 的字典,LoadResourceInfo 填充,加载前用于查资源归属包与路径
50属性Asset 加载器实例,负责单资源、目录、分帧预加载和资源缓存释放。
52方法返回内部创建的 Asset 加载器实例,供上层直接发起具体加载。
57属性Bundle 加载器,默认通用实现,入口可替换为寻物实现。
59属性初始化标记,控制配置与加载器只能在启动装配阶段替换。
61方法返回当前 Bundle 加载器,可能已被入口替换为寻物专用实现。
66方法在初始化前替换 Bundle 加载器,已初始化后调用会抛错。
73方法校验配置存在,设置引擎下载器重试次数与间隔,调用加载器 Init 并标记已初始化。
75注释初始化边界检查,未注入时不能继续启动资源模块。
82注释配置 Cocos 内置下载器重试参数 downloader.maxRetryCount 默认 3,retryInterval 默认 2000ms 可根据网络环境调整,如弱网场景增大 maxRetryCount
85注释专项下载适配由选中的加载器负责,管理器不依赖具体游戏。
91方法释放 Asset 缓存,反初始化并重建默认 Bundle 加载器,清除初始化标记但保留配置引用。
93注释重启时清理包内资源缓存,避免复用已被引擎释放的资源。
96注释管理器单例跨重启保留;新启动重新装配,不能沿用上一项目的专项实现。
99注释配置引用保留给后续退出日志/回调读取;下次入口仍会在同步前注入。
101方法每帧把 deltaTime 交给 Asset 加载器,驱动其分帧预加载任务队列。
103注释驱动 AssetLoader 的每帧更新(用于分帧预加载等任务)
114方法调用解析器把 JSON 资源清单写入内部字典,重复调用会合并覆盖同名条目。
124方法先查清单字典,未命中再问 Bundle 加载器按命名规则解析,都失败打错误返回空。
130注释清单未覆盖的资源交给当前加载器解析,管理器不识别项目命名。
141方法遍历引擎全局资源表,逐个打印引用计数与资源对象,最后打印资源总数。
152方法按渠道调用抖音 triggerGC 或系统 garbageCollect,并统计调用耗时写警告日志。
173注释======================================== 远程资源加载========================================
174属性远程加载失败记录,按 url 保存失败次数与最近失败时间。
193方法按调用方重试次数循环加载远程资源,成功即返回,耗尽后记录失败并返回空。
231方法按 url 累加失败次数并更新最近失败时间,随后清理过期条目。
242方法遍历失败记录,删除最近失败时间超过一分钟的条目。
252方法先清理过期记录,再返回该地址的失败次数与最近失败时间。
262方法生成链路 id 并把加载请求转交 Bundle 加载器,完成后打印耗时并返回 Bundle。
270注释一次资源加载链路,从 ResourceManager 开始创建 TraceId
293方法先让 Asset 加载器释放在该包内的缓存资源,再让 Bundle 加载器释放包本身。
295注释委托 AssetLoader 清理该 Bundle 下的资源缓存
303方法先释放所有 Bundle 实例,再清空 Asset 加载器的全部资源缓存。
305注释调用加载器释放所有 Bundle 实例
308注释调用Asset加载器释放所有资源
320方法清单为空时向完成回调报错,否则生成链路 id 并委托 Asset 加载器预加载。
339方法清单为空时返回 reject,否则委托 Asset 加载器的异步预加载并透传链路 id。
358方法生成链路 id 并委托 Asset 加载器预加载指定 Bundle 内的目录。
374方法取默认批次一与并发二后委托分帧预加载,进度与完成回调原样透传。
411方法生成链路 id 并委托 Asset 加载器加载 Bundle 内整个目录。
425方法生成链路 id 并直接返回 Asset 加载器目录加载的 Promise。
436方法先按资源名加载图集,再按子图名取 SpriteFrame,图集为空或清单未加载时返回空。
442注释未打包(编辑器 / 预览 / 浏览器调试等)一律直接按图片名加载,方便开发 if (!BUILD) { return this.LoadAssetAsync<SpriteFrame>(spriteName, SpriteFrame); }
457注释通过现有 LoadAssetAsync 加载 / 复用图集(内部带有缓存与日志)
474注释if (!frame) { Framework.Log.TraceError( traceId, this.Name, "LoadSpriteFrameFromAtlas", `图集中不存在子图: ${spriteName}(atlas=${atlasAssetName})` ); return null; }
485方法依次尝试多个图集,全部未命中时退化为按贴图名直接加载 SpriteFrame。
492注释1. 依次从所有图集中查找子图
500注释2. 所有图集都没找到,退化为直接按贴图名加载 SpriteFrame(通常对应独立 png)
511注释3. 图集与独立贴图都加载失败,视为真正缺失
526方法清单为空时打错误返回空,否则生成链路 id 并委托 Asset 加载器加载单资源。
544方法清单为空时返回空,否则生成链路 id 并返回 Asset 加载器的异步加载 Promise。
560方法把资源名转交 Asset 加载器,由它释放引擎资源并删除缓存条目。
568方法先释放所有 Bundle,再清空 Asset 加载器缓存,是私有的全量清理入口。
570注释释放所有 Bundle
572注释释放所有资源