using System.Collections.Generic; using UnityEngine; public static class GameObjectPool { private static GameObject PoolAttach; private static Dictionary> s_poolMap = new Dictionary>(); private static Dictionary s_instanceToSrc = new Dictionary(); public static GameObject GetInstance(GameObject prefabSrc, Transform parent) { if (PoolAttach == null) { PoolAttach = new GameObject("[GameObjectPool]"); PoolAttach.transform.localScale = Vector3.zero; GameObject.DontDestroyOnLoad(PoolAttach); } if (!s_poolMap.ContainsKey(prefabSrc)) s_poolMap[prefabSrc] = new Queue(); GameObject instance = null; var pool = s_poolMap[prefabSrc]; if (pool.Count > 0) { instance = pool.Dequeue(); instance.transform.SetParent(parent, true); instance.transform.localScale = prefabSrc.transform.localScale; instance.transform.localRotation = prefabSrc.transform.localRotation; instance.transform.localPosition = prefabSrc.transform.localPosition; } else { instance = GameObject.Instantiate(prefabSrc, parent); s_instanceToSrc[instance] = prefabSrc; } //instance.SetActive(true); return instance; } public static void Release(GameObject instance) { s_instanceToSrc.TryGetValue(instance, out var src); if (src != null && s_poolMap.TryGetValue(src, out var pool)) { pool.Enqueue(instance); //instance.SetActive(false); if (instance == null) return; if (PoolAttach == null) return; instance.transform.SetParent(PoolAttach.transform, true); } else { GameObject.Destroy(instance); } } }