GameConfigData.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. using System;
  2. using System.Linq;
  3. using System.Reflection;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using Newtonsoft.Json.Linq;
  7. using System.Collections.Generic;
  8. using UnityEngine;
  9. /// <summary>
  10. /// 游戏配置数据
  11. /// </summary>
  12. sealed public partial class GameConfigData
  13. {
  14. #region ' 单例 '
  15. private static GameConfigData _ins = null;
  16. public static GameConfigData Ins
  17. {
  18. get
  19. {
  20. if (null == _ins)
  21. {
  22. LogHelper.LogError("配置数据尚未初始化!");
  23. }
  24. return _ins;
  25. }
  26. }
  27. /// <summary>
  28. /// 私有构造函数
  29. /// </summary>
  30. /// <param name="arg"></param>
  31. private GameConfigData(JObject arg = null)
  32. {
  33. System.Diagnostics.Trace.Assert(null != arg, "初始化数据不可为空!");
  34. data = arg;
  35. }
  36. private static JObject data;
  37. #endregion
  38. /// <summary>
  39. /// 配置数据是否已加载
  40. /// </summary>
  41. public static bool IsReady => _ins != null;
  42. /// <summary>
  43. /// 初始化方法, 无法在外部通过构造函数创建实例, 只能通过init方法初始化单例.
  44. /// </summary>
  45. /// <param name="arg"></param>
  46. public static void Init(JObject arg = null)
  47. {
  48. _ins = new GameConfigData(arg);
  49. if (null != _ins)
  50. {
  51. Thread t = new Thread(() =>
  52. {
  53. var st = DateTimeOffset.Now;
  54. LogHelper.Log(" 后台线程触发deserialize 开始");
  55. //_ins.touchEveryProperty(); // 没用!不挣扎了...还是用反射吧,反射性能更好.--gwang
  56. var tp = typeof(GameConfigData);
  57. var pps = tp.GetProperties();
  58. Parallel.ForEach<PropertyInfo>(pps, p => // 并行实例化(反序列化到强类型)各个模块的数据
  59. {
  60. if (p.GetCustomAttribute<sm_modPropAttribute>() != null)
  61. {
  62. _ = p.GetValue(_ins);
  63. }
  64. });
  65. LogHelper.Log($" 后台线程触发deserialize 结束. 耗时: {(DateTimeOffset.Now - st).TotalMilliseconds:.00}ms");
  66. });
  67. t.IsBackground = true;
  68. t.Start();
  69. }
  70. }
  71. /// <summary>
  72. /// 指示这是一个模块属性
  73. /// </summary>
  74. [AttributeUsage(AttributeTargets.Property)]
  75. partial class sm_modPropAttribute : Attribute
  76. {
  77. }
  78. #region ' 辅助方法 '
  79. private static T _moGetById<K, T>(K id, Dictionary<K, T> dic, string desc = "对象") where T : class
  80. {
  81. if (!dic.TryGetValue(id, out T ret))
  82. {
  83. LogHelper.LogWarning(string.Format("未找到{0}配置【{1}】", desc, id.ToString()));
  84. return null;
  85. }
  86. return ret;
  87. }
  88. #endregion
  89. }