ObjectPoolModule.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using KairoEngine.Core;
  6. using KairoEngine.Core.ModuleSystem;
  7. using Sirenix.OdinInspector;
  8. using QFSW.MOP2;
  9. namespace KairoEngine.Core.ObjectPooling
  10. {
  11. public class ObjectPoolModule : GameModuleBase
  12. {
  13. public override string name => "Object Pool Module";
  14. public List<ObjectPool> pools = new List<ObjectPool>();
  15. [SerializeField, HideInInspector] private int poolCount;
  16. public ObjectPoolModule(GameConfig config) : base(config)
  17. {
  18. this.gameConfig = config;
  19. this.className = this.GetType().AssemblyQualifiedName;
  20. this.typeName = "ObjectPoolModule";
  21. }
  22. public override void Load(Transform parent)
  23. {
  24. GameObject ObjectPoolPrefab = Resources.Load("ObjectPoolPrefab") as GameObject;
  25. if(ObjectPoolPrefab == null)
  26. {
  27. Debug.LogError("Could not find ObjectPoolPrefab in ObjectPoolModule");
  28. return;
  29. }
  30. GameObject objectPoolObj = GameObject.Instantiate(ObjectPoolPrefab, parent);
  31. objectPoolObj.name = "ObjectPool";
  32. MasterObjectPooler masterObjectPooler = objectPoolObj.GetComponent<MasterObjectPooler>();
  33. if(masterObjectPooler == null)
  34. {
  35. Debug.LogError("Could not find MasterObjectPooler component", objectPoolObj);
  36. return;
  37. }
  38. for (int i = 0; i < pools.Count; i++)
  39. {
  40. masterObjectPooler.AddPool(pools[i]);
  41. }
  42. }
  43. public override void Reset()
  44. {
  45. pools = new List<ObjectPool>();
  46. poolCount = 0;
  47. }
  48. public override void Destroy()
  49. {
  50. }
  51. public static ObjectPoolModule JSONToObjectPoolModule(string data)
  52. {
  53. try
  54. {
  55. return JsonUtility.FromJson<ObjectPoolModule>(data);
  56. }
  57. catch (System.Exception e)
  58. {
  59. Debug.LogError($"Could not deserialize ObjectPoolModule: \n{e}");
  60. }
  61. return new ObjectPoolModule(null);
  62. }
  63. public override void OnBeforeSerialize(ObjectSerializer serializer)
  64. {
  65. if(pools != null)
  66. {
  67. poolCount = pools.Count;
  68. for (int i = 0; i < pools.Count; i++)
  69. {
  70. serializer.AddObject($"ObjectPool_pool_{i}", pools[i]);
  71. }
  72. }
  73. }
  74. public override void OnBeforeDeserialize(ObjectSerializer serializer)
  75. {
  76. pools = new List<ObjectPool>();
  77. for (int i = 0; i < poolCount; i++)
  78. {
  79. pools.Add((ObjectPool)serializer.GetObject($"ObjectPool_pool_{i}"));
  80. }
  81. }
  82. }
  83. }