72 lines
2.4 KiB
C#
72 lines
2.4 KiB
C#
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<string, object> Data = new Dictionary<string, object>();
|
|
|
|
|
|
private ConfigMgr()
|
|
{
|
|
// 使用 Resources.Load 加载 JSON 数据
|
|
TextAsset jsonAsset = Resources.Load<TextAsset>("Configs/game_data");
|
|
if (jsonAsset == null)
|
|
{
|
|
throw new Exception("配置文件未找到: Resources/Configs/game_data.json");
|
|
}
|
|
|
|
string json = jsonAsset.text;
|
|
var gameData = JsonConvert.DeserializeObject<Dictionary<string, object>>(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<T> 类型
|
|
var listType = typeof(List<>).MakeGenericType(configType);
|
|
var configListInstance = JsonConvert.DeserializeObject(sheetData, listType);
|
|
Data[sheetName] = configListInstance;
|
|
}
|
|
}
|
|
}
|
|
|
|
public List<T> GetConfigList<T>() where T : class
|
|
{
|
|
// 从泛型类型名称中自动提取配置键
|
|
string key = typeof(T).Name.Replace("Config", "");
|
|
if (Data.ContainsKey(key))
|
|
{
|
|
return Data[key] as List<T>;
|
|
}
|
|
Debug.LogWarning($"未找到对应的配置实例: {key}");
|
|
return null;
|
|
}
|
|
|
|
public T GetConfig<T>(int id) where T : class
|
|
{
|
|
// 从泛型类型名称中自动提取配置键
|
|
string key = typeof(T).Name.Replace("Config", "");
|
|
if (Data.ContainsKey(key))
|
|
{
|
|
var list = Data[key] as List<T>;
|
|
return list?.FirstOrDefault(item => (int)item.GetType().GetProperty("id").GetValue(item) == id);
|
|
}
|
|
Debug.LogWarning($"未找到对应的配置实例: {key}");
|
|
return null;
|
|
}
|
|
}
|
|
}
|