PoolManager.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class PoolManager : MonoBehaviour
  5. {
  6. public static PoolManager instance;
  7. public Dictionary<GameObject, List<GameObject>> pools;
  8. void Awake()
  9. {
  10. if (instance)
  11. {
  12. Destroy(gameObject);
  13. return;
  14. }
  15. instance = this;
  16. pools = new Dictionary<GameObject, List<GameObject>>();
  17. }
  18. public static GameObject Instantiate(GameObject prefab, Vector3 pos = default, Quaternion rotation = default, Transform parent = null)
  19. {
  20. GameObject go;
  21. if (!instance)
  22. {
  23. go = Object.Instantiate(prefab, pos, rotation, parent);
  24. go.SetActive(true);
  25. return go;
  26. }
  27. if (instance.pools.ContainsKey(prefab) && instance.pools[prefab].Count > 0)
  28. {
  29. go = instance.pools[prefab][0];
  30. go.transform.parent = parent;
  31. go.transform.position = pos;
  32. go.transform.rotation = rotation;
  33. instance.pools[prefab].RemoveAt(0);
  34. }
  35. else
  36. {
  37. go = Object.Instantiate(prefab, pos, rotation, parent);
  38. PoolItem poolItem = go.AddComponent<PoolItem>();
  39. poolItem.prefab = prefab;
  40. }
  41. go.SetActive(true);
  42. return go;
  43. }
  44. public void Recycle(PoolItem poolItem)
  45. {
  46. if (!pools.ContainsKey(poolItem.prefab))
  47. {
  48. pools.Add(poolItem.prefab, new List<GameObject>());
  49. }
  50. pools[poolItem.prefab].Add(poolItem.gameObject);
  51. }
  52. public void DestroyItem(PoolItem poolItem)
  53. {
  54. if (!pools.ContainsKey(poolItem.prefab))
  55. {
  56. return;
  57. }
  58. pools[poolItem.prefab].Remove(poolItem.gameObject);
  59. }
  60. }