1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- using System;
- using System.Linq;
- using System.Reflection;
- using System.Threading;
- using System.Threading.Tasks;
- using Newtonsoft.Json.Linq;
- using System.Collections.Generic;
- using UnityEngine;
- /// <summary>
- /// 游戏配置数据
- /// </summary>
- sealed public partial class GameConfigData
- {
- #region ' 单例 '
- private static GameConfigData _ins = null;
- public static GameConfigData Ins
- {
- get
- {
- if (null == _ins)
- {
- LogHelper.LogError("配置数据尚未初始化!");
- }
- return _ins;
- }
- }
- /// <summary>
- /// 私有构造函数
- /// </summary>
- /// <param name="arg"></param>
- private GameConfigData(JObject arg = null)
- {
- System.Diagnostics.Trace.Assert(null != arg, "初始化数据不可为空!");
- data = arg;
- }
- private static JObject data;
- #endregion
- /// <summary>
- /// 配置数据是否已加载
- /// </summary>
- public static bool IsReady => _ins != null;
- /// <summary>
- /// 初始化方法, 无法在外部通过构造函数创建实例, 只能通过init方法初始化单例.
- /// </summary>
- /// <param name="arg"></param>
- public static void Init(JObject arg = null)
- {
- _ins = new GameConfigData(arg);
- if (null != _ins)
- {
- Thread t = new Thread(() =>
- {
- var st = DateTimeOffset.Now;
- LogHelper.Log(" 后台线程触发deserialize 开始");
- //_ins.touchEveryProperty(); // 没用!不挣扎了...还是用反射吧,反射性能更好.--gwang
- var tp = typeof(GameConfigData);
- var pps = tp.GetProperties();
- Parallel.ForEach<PropertyInfo>(pps, p => // 并行实例化(反序列化到强类型)各个模块的数据
- {
- if (p.GetCustomAttribute<sm_modPropAttribute>() != null)
- {
- _ = p.GetValue(_ins);
- }
- });
- LogHelper.Log($" 后台线程触发deserialize 结束. 耗时: {(DateTimeOffset.Now - st).TotalMilliseconds:.00}ms");
- });
- t.IsBackground = true;
- t.Start();
- }
- }
- /// <summary>
- /// 指示这是一个模块属性
- /// </summary>
- [AttributeUsage(AttributeTargets.Property)]
- partial class sm_modPropAttribute : Attribute
- {
- }
- #region ' 辅助方法 '
- private static T _moGetById<K, T>(K id, Dictionary<K, T> dic, string desc = "对象") where T : class
- {
- if (!dic.TryGetValue(id, out T ret))
- {
- LogHelper.LogWarning(string.Format("未找到{0}配置【{1}】", desc, id.ToString()));
- return null;
- }
- return ret;
- }
- #endregion
- }
|