using System.Collections.Generic; using System; using UnityEngine; public class ObjectPool { /// /// 池的堆栈 /// private readonly Stack m_Inactived = new Stack(); /// /// 池对象总数,包括已激活和未激活 /// public int totalCount; /// /// 取得当前还有多少激活对象 /// public int activedCount { get { return totalCount - inactivedCount; } } /// /// 取得池里还有多少对象 /// public int inactivedCount { get { return m_Inactived.Count; } } private Action m_OnObjectGet;// 供外部传入的回调方法,在获取对象的时候对该对象进行一些可能是初始化的操作 private Action m_OnObjectRelease;// 供外部传入的回调方法,在释放对象的时候对该对象进行一些可能是重置的操作 public ObjectPool(Action onGetAction, Action onReleaseAction) { m_OnObjectGet = onGetAction; m_OnObjectRelease = onReleaseAction; } public void Add(T element) { m_Inactived.Push(element); totalCount++; } public T Get() { T element; // 错误保护 if (inactivedCount == 0) { Debug.LogWarningFormat("获取池对象时,池已经为空."); return default(T); } // 取得池对象 element = m_Inactived.Pop(); // 执行获取逻辑 if (m_OnObjectGet != null) { m_OnObjectGet(element); } return element; } public void Release(T element) { // 错误保护 if (inactivedCount > 0 && ReferenceEquals(element, m_Inactived.Peek())) { Debug.LogWarningFormat("向池释放对象的时候发现,该对象已经被释放了.", element.ToString()); return; } // 执行外部传入的释放逻辑 if (m_OnObjectRelease != null) { m_OnObjectRelease(element); } m_Inactived.Push(element); } public void Clear() { m_Inactived.Clear(); } }