| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109 |
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class ObjectPoolManager : BaseManager<ObjectPoolManager>
- {
- private GameObject CachePanel;
- private Dictionary<string, Queue<GameObject>> m_Pool = new Dictionary<string, Queue<GameObject>>();
- private Dictionary<GameObject, string> m_GoTag = new Dictionary<GameObject, string>();
- /// <summary>
- /// 清空缓存池,释放所有引用
- /// </summary>
- public void ClearCachePool()
- {
- m_Pool.Clear();
- m_GoTag.Clear();
- }
- /// <summary>
- /// 回收GameObject
- /// </summary>
- 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<GameObject>();
- }
- m_Pool[tag].Enqueue(go);
- }
- }
- /// <summary>
- /// 请求GameObject
- /// </summary>
- public GameObject RequestCacheGameObejct(GameObject prefab)
- {
- string tag = prefab.GetInstanceID().ToString();
- GameObject go = GetFromPool(tag);
- if (go == null)
- {
- go = GameObject.Instantiate<GameObject>(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");
- }
- }
- }
|