using System.Collections; using System.Collections.Generic; using UnityEngine; public class ObjectPoolManager : MonoBehaviour { public static ObjectPoolManager Instance { get; private set; } // 多个对象池,每种类型一个 Queue private Dictionary> poolDict = new Dictionary>(); // 记录每种类型的原始 prefab // private Dictionary prefabDict = new Dictionary(); private void Awake() { if (Instance == null) Instance = this; else Destroy(gameObject); DontDestroyOnLoad(gameObject); // 保持池子跨场景有效 } /// /// 获取一个对象(从对象池中或新建) /// public GameObject Get(string key, GameObject prefab, Transform parent = null) { if (!poolDict.ContainsKey(key)) { poolDict[key] = new Queue(); // prefabDict[key] = prefab; } GameObject obj; if (poolDict[key].Count > 0) { obj = poolDict[key].Dequeue(); } else { // obj = Instantiate(prefabDict[key]); obj = Instantiate(prefab); } obj.SetActive(true); if (parent != null) obj.transform.SetParent(parent); return obj; } /// /// 回收一个对象(回到池中) /// public void Release(string key, GameObject obj) { if (!poolDict.ContainsKey(key)) { Debug.LogWarning("ObjectPoolManager: 没有这个 key 的对象池:" + key); Destroy(obj); return; } obj.SetActive(false); obj.transform.SetParent(transform); // 可统一收纳到 manager 下 poolDict[key].Enqueue(obj); } /// /// 清除所有池(可用于重启/清场) /// public void ClearAllPools() { foreach (var queue in poolDict.Values) { while (queue.Count > 0) { GameObject obj = queue.Dequeue(); Destroy(obj); } } poolDict.Clear(); // prefabDict.Clear(); } }