ConfigHolder.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using UnityEngine;
  5. namespace Fort23.GameData
  6. {
  7. public abstract class ConfigHolder
  8. {
  9. public abstract Type ConfigType { get; }
  10. public abstract IConfig GetFirst();
  11. public abstract List<IConfig> GetAll();
  12. public abstract IConfig TryGet(int type);
  13. public abstract void SetConfig(List<IConfig> config);
  14. public virtual void Init()
  15. {
  16. }
  17. }
  18. /// <summary>
  19. /// 管理所有的配置
  20. /// </summary>
  21. /// <typeparam name="T"></typeparam>
  22. [Serializable]
  23. public abstract class ConfigHolder<T> : ConfigHolder where T : IConfig
  24. {
  25. public List<T> configList;
  26. private Dictionary<int, IConfig> _dictionary;
  27. public override void Init()
  28. {
  29. _dictionary = new Dictionary<int, IConfig>();
  30. foreach (var config in configList)
  31. {
  32. _dictionary.Add(config.GetID(), config);
  33. }
  34. }
  35. public override void SetConfig(List<IConfig> config)
  36. {
  37. if (configList != null)
  38. {
  39. return;
  40. }
  41. configList = new List<T>();
  42. for (int i = 0; i < config.Count; i++)
  43. {
  44. configList.Add((T) config[i]);
  45. }
  46. }
  47. public override Type ConfigType
  48. {
  49. get { return typeof(T); }
  50. }
  51. public override IConfig TryGet(int ID)
  52. {
  53. if (ID <= 0)
  54. {
  55. Debug.Log($"在表{typeof(T)}中没有找到ID:{ID}");
  56. return null;
  57. }
  58. IConfig t;
  59. if (!_dictionary.TryGetValue(ID, out t))
  60. {
  61. Debug.Log($"在表{typeof(T)}中没有找到ID:{ID}————{_dictionary.Count}");
  62. return null;
  63. }
  64. return t;
  65. }
  66. public override List<IConfig> GetAll()
  67. {
  68. List<IConfig> configs = _dictionary.Values.ToList();
  69. return configs;
  70. }
  71. public override IConfig GetFirst()
  72. {
  73. return _dictionary.Values.First();
  74. }
  75. }
  76. }