ConfigLoader.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System;
  2. using System.Collections.Generic;
  3. #if DOTNET || UNITY_STANDALONE
  4. using System.Threading.Tasks;
  5. #endif
  6. namespace ET
  7. {
  8. /// <summary>
  9. /// ConfigLoader会扫描所有的有ConfigAttribute标签的配置,加载进来
  10. /// </summary>
  11. public class ConfigLoader : Singleton<ConfigLoader>, ISingletonAwake
  12. {
  13. public struct GetAllConfigBytes
  14. {
  15. }
  16. public struct GetOneConfigBytes
  17. {
  18. public string ConfigName;
  19. }
  20. public void Awake()
  21. {
  22. }
  23. public async ETTask Reload(Type configType)
  24. {
  25. GetOneConfigBytes getOneConfigBytes = new() { ConfigName = configType.Name };
  26. byte[] oneConfigBytes = await EventSystem.Instance.Invoke<GetOneConfigBytes, ETTask<byte[]>>(getOneConfigBytes);
  27. LoadOneConfig(configType, oneConfigBytes);
  28. ConfigProcess();
  29. }
  30. public async ETTask LoadAsync()
  31. {
  32. Dictionary<Type, byte[]> configBytes = await EventSystem.Instance.Invoke<GetAllConfigBytes, ETTask<Dictionary<Type, byte[]>>>(new GetAllConfigBytes());
  33. #if DOTNET || UNITY_STANDALONE
  34. using ListComponent<Task> listTasks = ListComponent<Task>.Create();
  35. foreach (Type type in configBytes.Keys)
  36. {
  37. byte[] oneConfigBytes = configBytes[type];
  38. Task task = Task.Run(() => LoadOneConfig(type, oneConfigBytes));
  39. listTasks.Add(task);
  40. }
  41. await Task.WhenAll(listTasks.ToArray());
  42. #else
  43. foreach (Type type in configBytes.Keys)
  44. {
  45. LoadOneConfig(type, configBytes[type]);
  46. }
  47. #endif
  48. ConfigProcess();
  49. }
  50. private static void LoadOneConfig(Type configType, byte[] oneConfigBytes)
  51. {
  52. object category = MongoHelper.Deserialize(configType, oneConfigBytes, 0, oneConfigBytes.Length);
  53. ASingleton singleton = category as ASingleton;
  54. World.Instance.AddSingleton(singleton);
  55. }
  56. private void ConfigProcess()
  57. {
  58. var hashSet = CodeTypes.Instance.GetTypes(typeof (ConfigProcessAttribute));
  59. foreach (Type type in hashSet)
  60. {
  61. object obj = Activator.CreateInstance(type);
  62. ((ISingletonAwake)obj).Awake();
  63. World.Instance.AddSingleton((ASingleton)obj);
  64. }
  65. }
  66. }
  67. }