1
0

Pool.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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.SetActive(true);
  43. active.Add(item);
  44. return item;
  45. }
  46. public void ReturnToPool(GameObject item)
  47. {
  48. if (active.Remove(item))
  49. {
  50. item.SetActive(false);
  51. inactive.Enqueue(item);
  52. }
  53. }
  54. }
  55. }