using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using Object = UnityEngine.Object; namespace Pools { public class Pool : MonoBehaviour { public int initialSize = 10; public int amountIncrease = 5; public GameObject prefab; private Queue inactive; private HashSet active; private void Awake() { active = new HashSet(); inactive = new Queue(); IncreasePool(initialSize); } private void IncreasePool(int amount) { for (var i = 0; i < amount; i++) { var item = Instantiate(prefab, transform); item.SetActive(false); inactive.Enqueue(item); } } public GameObject GetItem() { GameObject item; if (inactive.Count > 0) { item = inactive.Dequeue(); } else { IncreasePool(amountIncrease); item = inactive.Dequeue(); } item.transform.SetPositionAndRotation(Vector3.zero, Quaternion.Euler(Vector3.zero)); item.SetActive(true); active.Add(item); return item; } public void ReturnToPool(GameObject item) { if (active.Remove(item)) { item.SetActive(false); inactive.Enqueue(item); } } } }