using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using Newtonsoft.Json; namespace BigSpace.XRCore.Config { public class ConfigMgr { private static ConfigMgr _instance; public static ConfigMgr Instance => _instance ??= new ConfigMgr(); private Dictionary Data = new Dictionary(); private ConfigMgr() { // 使用 Resources.Load 加载 JSON 数据 TextAsset jsonAsset = Resources.Load("Configs/game_data"); if (jsonAsset == null) { throw new Exception("配置文件未找到: Resources/Configs/game_data.json"); } string json = jsonAsset.text; var gameData = JsonConvert.DeserializeObject>(json); foreach (var sheet in gameData) { var sheetName = sheet.Key; var sheetData = sheet.Value.ToString(); // 动态初始化配置类 var configType = Type.GetType($"BigSpace.XRCore.Config.{sheetName}Config"); if (configType != null) { // 使用泛型 List 类型 var listType = typeof(List<>).MakeGenericType(configType); var configListInstance = JsonConvert.DeserializeObject(sheetData, listType); Data[sheetName] = configListInstance; } } } public List GetConfigList() where T : class { // 从泛型类型名称中自动提取配置键 string key = typeof(T).Name.Replace("Config", ""); if (Data.ContainsKey(key)) { return Data[key] as List; } Debug.LogWarning($"未找到对应的配置实例: {key}"); return null; } public T GetConfig(int id) where T : class { // 从泛型类型名称中自动提取配置键 string key = typeof(T).Name.Replace("Config", ""); if (Data.ContainsKey(key)) { var list = Data[key] as List; return list?.FirstOrDefault(item => (int)item.GetType().GetProperty("id").GetValue(item) == id); } Debug.LogWarning($"未找到对应的配置实例: {key}"); return null; } } }