2
0

Pool.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. namespace Pools
  4. {
  5. public class Pool : MonoBehaviour
  6. {
  7. public int initialSize = 10;
  8. public int amountIncrease = 5;
  9. public GameObject prefab;
  10. private HashSet<GameObject> active;
  11. private Queue<GameObject> inactive;
  12. private void Awake()
  13. {
  14. active = new HashSet<GameObject>();
  15. inactive = new Queue<GameObject>();
  16. IncreasePool(initialSize);
  17. }
  18. private void IncreasePool(int amount)
  19. {
  20. for (var i = 0; i < amount; i++)
  21. {
  22. var item = Instantiate(prefab, transform);
  23. item.SetActive(false);
  24. inactive.Enqueue(item);
  25. }
  26. }
  27. public GameObject GetItem()
  28. {
  29. GameObject item;
  30. if (inactive.Count > 0)
  31. {
  32. item = inactive.Dequeue();
  33. }
  34. else
  35. {
  36. IncreasePool(amountIncrease);
  37. item = inactive.Dequeue();
  38. }
  39. item.transform.SetPositionAndRotation(Vector3.zero, Quaternion.Euler(Vector3.zero));
  40. item.SetActive(true);
  41. active.Add(item);
  42. return item;
  43. }
  44. public void ReturnToPool(GameObject item)
  45. {
  46. if (active.Remove(item))
  47. {
  48. item.SetActive(false);
  49. inactive.Enqueue(item);
  50. }
  51. }
  52. }
  53. }