using System.Collections; using System.Collections.Generic; using UnityEngine; public class ObjectPoolManager : BaseManager { private GameObject CachePanel; private Dictionary> m_Pool = new Dictionary>(); private Dictionary m_GoTag = new Dictionary(); /// /// 清空缓存池,释放所有引用 /// public void ClearCachePool() { m_Pool.Clear(); m_GoTag.Clear(); } /// /// 回收GameObject /// public void ReturnCacheGameObejct(GameObject go) { if (CachePanel == null) { CachePanel = new GameObject(); CachePanel.name = "CachePanel"; GameObject.DontDestroyOnLoad(CachePanel); } if (go == null) { return; } go.transform.SetParent(CachePanel.transform); go.SetActive(false); if (m_GoTag.ContainsKey(go)) { string tag = m_GoTag[go]; RemoveOutMark(go); if (!m_Pool.ContainsKey(tag)) { m_Pool[tag] = new Queue(); } m_Pool[tag].Enqueue(go); } } /// /// 请求GameObject /// public GameObject RequestCacheGameObejct(GameObject prefab) { string tag = prefab.GetInstanceID().ToString(); GameObject go = GetFromPool(tag); if (go == null) { go = GameObject.Instantiate(prefab); go.name = prefab.name + Time.time; } MarkAsOut(go, tag); return go; } private GameObject GetFromPool(string tag) { if (m_Pool.ContainsKey(tag) && m_Pool[tag].Count > 0) { GameObject obj = m_Pool[tag].Dequeue(); obj.SetActive(true); return obj; } else { return null; } } private void MarkAsOut(GameObject go, string tag) { m_GoTag.Add(go, tag); } private void RemoveOutMark(GameObject go) { if (m_GoTag.ContainsKey(go)) { m_GoTag.Remove(go); } else { Debug.LogError("remove out mark error, gameObject has not been marked"); } } }