1
0

Pool.cs 1.5 KB

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