ObjectPoolManager.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class ObjectPoolManager : BaseManager<ObjectPoolManager>
  5. {
  6. private GameObject CachePanel;
  7. private Dictionary<string, Queue<GameObject>> m_Pool = new Dictionary<string, Queue<GameObject>>();
  8. private Dictionary<GameObject, string> m_GoTag = new Dictionary<GameObject, string>();
  9. /// <summary>
  10. /// 清空缓存池,释放所有引用
  11. /// </summary>
  12. public void ClearCachePool()
  13. {
  14. m_Pool.Clear();
  15. m_GoTag.Clear();
  16. }
  17. /// <summary>
  18. /// 回收GameObject
  19. /// </summary>
  20. public void ReturnCacheGameObejct(GameObject go)
  21. {
  22. if (CachePanel == null)
  23. {
  24. CachePanel = new GameObject();
  25. CachePanel.name = "CachePanel";
  26. GameObject.DontDestroyOnLoad(CachePanel);
  27. }
  28. if (go == null)
  29. {
  30. return;
  31. }
  32. go.transform.SetParent(CachePanel.transform);
  33. go.SetActive(false);
  34. if (m_GoTag.ContainsKey(go))
  35. {
  36. string tag = m_GoTag[go];
  37. RemoveOutMark(go);
  38. if (!m_Pool.ContainsKey(tag))
  39. {
  40. m_Pool[tag] = new Queue<GameObject>();
  41. }
  42. m_Pool[tag].Enqueue(go);
  43. }
  44. }
  45. /// <summary>
  46. /// 请求GameObject
  47. /// </summary>
  48. public GameObject RequestCacheGameObejct(GameObject prefab)
  49. {
  50. string tag = prefab.GetInstanceID().ToString();
  51. GameObject go = GetFromPool(tag);
  52. if (go == null)
  53. {
  54. go = GameObject.Instantiate<GameObject>(prefab);
  55. go.name = prefab.name + Time.time;
  56. }
  57. MarkAsOut(go, tag);
  58. return go;
  59. }
  60. private GameObject GetFromPool(string tag)
  61. {
  62. if (m_Pool.ContainsKey(tag) && m_Pool[tag].Count > 0)
  63. {
  64. GameObject obj = m_Pool[tag].Dequeue();
  65. obj.SetActive(true);
  66. return obj;
  67. }
  68. else
  69. {
  70. return null;
  71. }
  72. }
  73. private void MarkAsOut(GameObject go, string tag)
  74. {
  75. m_GoTag.Add(go, tag);
  76. }
  77. private void RemoveOutMark(GameObject go)
  78. {
  79. if (m_GoTag.ContainsKey(go))
  80. {
  81. m_GoTag.Remove(go);
  82. }
  83. else
  84. {
  85. Debug.LogError("remove out mark error, gameObject has not been marked");
  86. }
  87. }
  88. }