using UnityEngine; using UnityEngine.Pool; public sealed class PrefabPoolLab : MonoBehaviour { [SerializeField] private GameObject inactivePrefab; private ObjectPool pool; private void Awake() { if (inactivePrefab == null || inactivePrefab.activeSelf) { Debug.LogError("Assign a prefab whose root is inactive.", this); enabled = false; return; } pool = new ObjectPool( () => Instantiate(inactivePrefab, transform), item => { item.transform.localPosition = Vector3.zero; item.SetActive(true); }, item => item.SetActive(false), item => { if (item != null) Destroy(item); }, true, 4, 16); } [ContextMenu("Rent And Return")] public void RentAndReturn() { if (!Application.isPlaying || pool == null) return; GameObject item = pool.Get(); Debug.Log("Borrowed instance: " + item.GetInstanceID(), item); pool.Release(item); Debug.Log("Created=" + pool.CountAll + ", Inactive=" + pool.CountInactive, this); } private void OnDestroy() { if (pool != null) pool.Dispose(); } }