using System.Collections.Generic;
|
using System;
|
using UnityEngine;
|
|
public class ObjectPool<T>
|
{
|
/// <summary>
|
/// 池的堆栈
|
/// </summary>
|
private readonly Stack<T> m_Inactived = new Stack<T>();
|
|
/// <summary>
|
/// 池对象总数,包括已激活和未激活
|
/// </summary>
|
public int totalCount;
|
|
/// <summary>
|
/// 取得当前还有多少激活对象
|
/// </summary>
|
public int activedCount
|
{
|
get
|
{
|
return totalCount - inactivedCount;
|
}
|
}
|
|
/// <summary>
|
/// 取得池里还有多少对象
|
/// </summary>
|
public int inactivedCount
|
{
|
get
|
{
|
return m_Inactived.Count;
|
}
|
}
|
|
private Action<T> m_OnObjectGet;// 供外部传入的回调方法,在获取对象的时候对该对象进行一些可能是初始化的操作
|
private Action<T> m_OnObjectRelease;// 供外部传入的回调方法,在释放对象的时候对该对象进行一些可能是重置的操作
|
|
public ObjectPool(Action<T> onGetAction, Action<T> 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();
|
}
|
}
|