GameModule.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. 
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using UnityEngine;
  6. using Sirenix.OdinInspector;
  7. namespace KairoEngine.Core.ModuleSystem
  8. {
  9. [System.Serializable, HideReferenceObjectPicker]
  10. public class GameModule : IComparable<GameModule>
  11. {
  12. [SerializeField, HideInInspector] public virtual string name => "Empty Module Slot";
  13. [SerializeField, HideInInspector] public string typeName = "GameModule";
  14. [SerializeField, HideInInspector] public string className;
  15. [InlineButton("Reset", "Reset")]
  16. [InlineButton("Remove", "Remove")]
  17. [FoldoutGroup("@name")] public bool enableModule = true;
  18. [HideInInspector] public bool isInitialized = false;
  19. [HideInInspector, NonSerialized] public GameConfig gameConfig;
  20. public GameModule(GameConfig config)
  21. {
  22. this.gameConfig = config;
  23. this.className = this.GetType().AssemblyQualifiedName;
  24. }
  25. public virtual void Load(Transform parent)
  26. {
  27. }
  28. public virtual void Reset()
  29. {
  30. }
  31. public virtual void Destroy()
  32. {
  33. }
  34. [FoldoutGroup("@name")]
  35. public virtual void Remove()
  36. {
  37. gameConfig.modules.Remove(this);
  38. }
  39. public virtual int CompareTo(GameModule other)
  40. {
  41. if(other == null) return 1;
  42. else return -1;
  43. }
  44. public static GameModuleBase InvokeStringMethod(string typeName, string methodName, string data)
  45. {
  46. Type calledType = Type.GetType(typeName);
  47. if(calledType == null)
  48. {
  49. Debug.LogError($"Could not find type: \"{typeName}\"");
  50. return null;
  51. }
  52. try
  53. {
  54. GameModuleBase module = (GameModuleBase)calledType.InvokeMember($"JSONTo{methodName}",
  55. System.Reflection.BindingFlags.InvokeMethod |
  56. System.Reflection.BindingFlags.Public |
  57. System.Reflection.BindingFlags.Static,
  58. null, null, new object[] { data });
  59. return module;
  60. }
  61. catch (System.Exception e)
  62. {
  63. Debug.LogError($"Error deserializing GameModule: \n{e}");
  64. return null;
  65. }
  66. }
  67. public static GameModule JSONToGameModule(string data)
  68. {
  69. return JsonUtility.FromJson<GameModule>(data);
  70. }
  71. public virtual void OnBeforeSerialize(ObjectSerializer serializer) { }
  72. public virtual void OnBeforeDeserialize(ObjectSerializer serializer) { }
  73. }
  74. [System.Serializable, HideReferenceObjectPicker]
  75. public class GameModuleBase : GameModule
  76. {
  77. public GameModuleBase(GameConfig config) : base(config)
  78. {
  79. this.gameConfig = config;
  80. this.className = this.GetType().AssemblyQualifiedName;
  81. this.typeName = "GameModuleBase";
  82. }
  83. }
  84. }