using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameObjectPool { private List m_FreeList; private List m_ActiveList; private GameObject m_Prefab; public int nameHashCode; public string name; public GameObjectPool(GameObject prefab) { name = prefab.name; nameHashCode = name.GetHashCode(); m_Prefab = prefab; m_FreeList = new List(); m_ActiveList = new List(); } public GameObject Request() { GameObject _gameObject = null; if (m_FreeList.Count == 0) { _gameObject = Object.Instantiate(m_Prefab); _gameObject.name = name; } else { _gameObject = m_FreeList[0]; m_FreeList.RemoveAt(0); } m_ActiveList.Add(_gameObject); return _gameObject; } public void Release(GameObject gameObject) { if (m_ActiveList.Contains(gameObject)) { m_ActiveList.Remove(gameObject); } else { DebugEx.LogWarningFormat("所回收的go对象 {0} 并不是从池里取得的...", gameObject.name); } m_FreeList.Add(gameObject); } public void Clear() { foreach (var _item in m_FreeList) { Object.Destroy(_item); } foreach (var _item in m_ActiveList) { Object.Destroy(_item); } m_FreeList.Clear(); m_ActiveList.Clear(); } public void Destroy() { Clear(); m_Prefab = null; m_FreeList = null; m_ActiveList = null; } #if UNITY_EDITOR public void ForeachActive(System.Action method) { for (int i = m_ActiveList.Count - 1; i >= 0; --i) { method(m_ActiveList[i]); } } public void ForeachFree(System.Action method) { for (int i = m_FreeList.Count - 1; i >= 0; --i) { method(m_FreeList[i]); } } #endif }