目录— 个文件
⌕
目录加载中…
…/core/config/ConfigManager.ts
1import { UIPanelFramePath } from "../ui/UIPanelFramePath";
2import { JsonAsset } from "cc";
3import { FrameworkEntry } from "../../FrameworkEntry";
4import { UICommonPopupText_Config } from "../ui/common/UICommonPopupFrameText";
5import { IFrameworkManager } from "../base/IFrameworkManager";
6import { Singleton } from "../base/Singleton";
7import { ResourceMode } from "../resource/ResourceFrameConfig";
8import { UtilityTime } from "../utility/UtilityTime";
9import { Framework } from "../../Framework";
10import { ConfigData } from "./ConfigFrameDefine";
11
12/** 公共配置统一加载服务;业务动作在配置准备完成后由启动流程执行。 */
13export class ConfigManager extends Singleton<ConfigManager> implements IFrameworkManager {
14 public Name: string = "ConfigManager";
15 /** 所有公共 JSON 的唯一容器;只在整批加载成功后替换。 */
16 private configs: Map<string, object> = new Map();
17 /** 入口提供唯一清单与实时目录规则,框架不创建项目默认配置。 */
18 private startupConfigs: readonly ConfigData[] | null = null;
19 private getRemoteRootPath: (() => string) | null = null;
20
21 /** 只保存引用,不加载配置;重启时由项目入口重新装配。 */
22 public SetStartupConfigs(configs: readonly ConfigData[], getRemoteRootPath: () => string): void {
23 this.startupConfigs = configs;
24 this.getRemoteRootPath = getRemoteRootPath;
25 }
26
27 /** 基础初始化不读取配置或玩家存档。 */
28 async Init(): Promise<void> {
29 this.configs.clear();
30 }
31
32 DeInit(): void {
33 this.configs.clear();
34 }
35
36 Update(_deltaTime: number): void {
37 }
38
39 /** 并发加载公共配置;失败弹窗重启并返回 false,调用方必须停止业务初始化。 */
40 public async LoadAllStartupConfigs(): Promise<boolean> {
41 // 装配遗漏是启动错误,不能以空清单伪装成配置加载成功。
42 if (!this.startupConfigs || !this.getRemoteRootPath) {
43 throw new Error("[ConfigManager] 请先通过 SetStartupConfigs 设置启动配置");
44 }
45 // 只在整批成功后发布,失败后的迟到响应不会写入共享配置。
46 const configs = new Map<string, object>();
47 try {
48 await Promise.all(this.startupConfigs.map(async data => {
49 const config = await this.LoadConfig<object>(data);
50 configs.set(data.Name, config);
51 }));
52 } catch (error) {
53 Framework.Log.Error(this.Name, "LoadAllStartupConfigs", "公共配置准备失败,请重启游戏", error);
54 // 直接通过 UI 管理器打开通用提示面板。
55 Framework.UI.OpenPanel(UIPanelFramePath.UICommonPopupPanel, {
56 title: UICommonPopupText_Config.Title,
57 content: UICommonPopupText_Config.Content,
58 btn2Text: UICommonPopupText_Config.Restart,
59 // 启动配置加载时入口实例已就绪,重启复用框架入口能力。
60 btn2Callback: () => FrameworkEntry.Instance!.RestartGame(),
61 showClose: false,
62 });
63 return false;
64 }
65 this.configs = configs;
66 Framework.Log.Log(this.Name, "LoadAllStartupConfigs", "公共配置和玩法总表已全部就绪");
67 return true;
68 }
69
70 /** 同步读取共享配置;新增配置无需再添加字段、setter 或专用 getter。 */
71 public GetConfig<T>(name: string): T {
72 const config = this.configs.get(name);
73 if (config === undefined) {
74 throw new Error(`[ConfigManager] 配置尚未加载: ${name}`);
75 }
76 return config as T;
77 }
78
79 /** 有远端路径的配置默认远程优先;本地资源模式或包级开关可强制读包内。 */
80 private async LoadConfig<T>(data: ConfigData): Promise<T> {
81 const flags = Framework.Package.GetCurrentPackageData().featureFlags;
82 const useRemote = Framework.Res.Config.ResourceMode === ResourceMode.Remote
83 && flags?.useLocalStartupConfigs !== true && !!data.RemotePath;
84 let config: T | null;
85 if (useRemote) {
86 // 加载时才解析目录,使用编辑器/发行包同步后的地址、环境和版本。
87 const url = `${this.getRemoteRootPath!()}${data.RemotePath}`;
88 config = await this.LoadRemoteConfig<T>(url, data.LocalAssetName);
89 } else {
90 config = await this.LoadLocalConfig<T>(data.LocalAssetName);
91 }
92 if (config === null) {
93 throw new Error(`[${this.Name}] 配置加载失败: ${data.LocalAssetName}`);
94 }
95 return config;
96 }
97
98 /** 远端加载、解析失败或内容为空时回退包内配置;单关点位也复用此入口。 */
99 public async LoadRemoteConfig<T>(
100 remotePath: string,
101 localAssetName: string,
102 ): Promise<T | null> {
103 const url = UtilityTime.AddTimestampToUrl(remotePath);
104 try {
105 const asset = await Framework.Res.LoadRemote<JsonAsset>({
106 url,
107 // 重试由 ResourceManager 统一控制:首次请求 + 2 次重试。
108 options: { type: JsonAsset, maxRetryCount: 0, retryInterval: 0 },
109 MaxRetryCount: 2,
110 RetryInterval: 300,
111 });
112 const config = asset?.json as T | null | undefined;
113 if (config == null) {
114 throw new Error("远端配置为空");
115 }
116 Framework.Log.Log(this.Name, "LoadRemoteConfig", `已加载远端配置: ${remotePath}`);
117 return config;
118 } catch (error) {
119 Framework.Log.Error(this.Name, "LoadRemoteConfig", `远端失败,回退本地: ${remotePath} -> ${localAssetName}`, error);
120 }
121 return this.LoadLocalConfig<T>(localAssetName);
122 }
123
124 /** 本地资源通过资源索引定位;失败显式返回 null,由总表或单关加载入口决定重试。 */
125 public async LoadLocalConfig<T>(localAssetName: string): Promise<T | null> {
126 try {
127 const asset = await Framework.Res.LoadAssetAsync<JsonAsset>(localAssetName, JsonAsset);
128 const config = asset?.json as T | null | undefined;
129 if (config == null) {
130 throw new Error("本地配置为空");
131 }
132 Framework.Log.Log(this.Name, "LoadLocalConfig", `已加载本地配置: ${localAssetName}`);
133 return config;
134 } catch (error) {
135 Framework.Log.Error(this.Name, "LoadLocalConfig", `本地配置加载失败: ${localAssetName}`, error);
136 return null;
137 }
138 }
139
140}
讲解141 行
公共配置加载服务人工通读
ConfigManager.ts
负责启动期公共 JSON 的批量加载。入口先注入清单和远端根路径,再由 LoadAllStartupConfigs 并发拉取,整批成功后一次性替换共享容器;单条按资源模式和包级开关选远端或包内,远端失败回退本地,整批失败弹窗要求重启。
按 SetStartupConfigs、Init、LoadAllStartupConfigs、LoadConfig、LoadRemoteConfig、LoadLocalConfig、GetConfig 的顺序读,注意容器替换的时机。
特殊处理与易错点
- 初始化顺序依赖清单或根路径函数任一缺失就抛错,不返回空配置,把装配遗漏当成启动错误而不是可忽略的降级。L42
- 缓存与销毁时机先用临时 Map 收集,Promise.all 全部成功后才赋值给 this.configs,失败时旧容器原样保留,迟到的响应不会写进共享配置。L46
- 渠道差异远端加载要同时满足资源模式为 Remote、马甲包 featureFlags.useLocalStartupConfigs 不为 true、且该项有 RemotePath 三个条件。L82
- 特殊处理远端地址在加载时才拼根路径并追加时间戳,根路径函数每次调用都会读取当前的地址、环境和版本,避免 CDN 缓存旧配置。L103
- 异常兜底外层 MaxRetryCount 为 2、内层 maxRetryCount 为 0,重试次数由 ResourceManager 统一控制,两处同时配置会叠加。L108
- 异常兜底整批失败时打开不可关闭的通用弹窗,按钮回调直接重启游戏,且返回 false,调用方必须停止后续业务初始化。L55
13注释ConfigManager:公共配置统一加载服务;业务动作在配置准备完成后由启动流程执行。
14属性管理器名称,日志与错误信息里作为模块标识。
16属性所有公共配置的唯一容器,键为 ConfigData.Name,只在整批成功后整体替换,GetConfig 读它。
18属性入口注入的只读配置清单,只保存引用不复制,重启时由入口重新装配。
22方法只保存配置清单和根路径函数两个引用,不触发任何加载,也不做格式校验。
28方法清空配置容器,不读取任何配置,避免启动阶段加载两遍。
32方法清空配置容器,不取消已经发出的加载请求,也不重置入口注入的清单引用。
36方法空实现,配置只在启动阶段批量加载,没有逐帧任务。
40方法并发加载清单里的每一项,全部成功后整体替换容器,任一失败弹通用提示框并返回失败。
42注释装配遗漏是启动错误,不能以空清单伪装成配置加载成功。
46注释只在整批成功后发布,失败后的迟到响应不会写入共享配置。
55注释直接通过 UI 管理器打开通用提示面板。
60注释启动配置加载时入口实例已就绪,重启复用框架入口能力。
71方法从容器同步取指定名称的配置对象,名未加载时直接抛错,不返回默认值。
80方法按资源模式、马甲包本地开关和是否有远端路径三项决定走远端或包内,远端地址由根路径函数拼接。
87注释加载时才解析目录,使用编辑器/发行包同步后的地址、环境和版本。
99方法给远端地址追加时间戳后加载 JsonAsset,失败或内容为空时回退到包内同名资源。
108注释重试由 ResourceManager 统一控制:首次请求 + 2 次重试。
125方法按资源索引名加载包内 JsonAsset 并取 json 字段,任何失败只记日志并返回 null。