PoolManager.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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.pools.ContainsKey(prefab) && instance.pools[prefab].Count > 0)
  22. {
  23. go = instance.pools[prefab][0];
  24. go.transform.parent = parent;
  25. go.transform.position = pos;
  26. go.transform.rotation = rotation;
  27. instance.pools[prefab].RemoveAt(0);
  28. }
  29. else
  30. {
  31. go = Object.Instantiate(prefab, pos, rotation, parent);
  32. PoolItem poolItem = go.AddComponent<PoolItem>();
  33. poolItem.prefab = prefab;
  34. }
  35. go.SetActive(true);
  36. return go;
  37. }
  38. public void Recycle(PoolItem poolItem)
  39. {
  40. if (!pools.ContainsKey(poolItem.prefab))
  41. {
  42. pools.Add(poolItem.prefab, new List<GameObject>());
  43. }
  44. pools[poolItem.prefab].Add(poolItem.gameObject);
  45. }
  46. public void DestroyItem(PoolItem poolItem)
  47. {
  48. if (!pools.ContainsKey(poolItem.prefab))
  49. {
  50. return;
  51. }
  52. pools[poolItem.prefab].Remove(poolItem.gameObject);
  53. }
  54. }