CoinPool.cs 1.5 KB

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