using System.Collections; using System.Collections.Generic; using UnityEngine; public class ObjectPool { protected Queue _pool = new Queue(); private GameObject _prefab; private Transform _parent; public ObjectPool(GameObject prefab, int initialSize, Transform parent) { _parent = parent; _prefab = prefab; for (int i = 0; i < initialSize; i++) { GameObject obj = GameObject.Instantiate(_prefab, _parent); obj.SetActive(false); _pool.Enqueue(obj); } } public GameObject Get() { if (_pool.Count > 0) { GameObject obj = _pool.Dequeue(); obj.SetActive(true); return obj; } else { // If there are no objects in the pool, create a new one. return GameObject.Instantiate(_prefab); } } public void Return(GameObject obj) { obj.SetActive(false); _pool.Enqueue(obj); } }