mirror of
https://github.com/tym1116/BH3.git
synced 2025-12-18 17:34:45 +01:00
71 lines
1.2 KiB
C#
71 lines
1.2 KiB
C#
using System.Collections.Generic;
|
|
using UnityEngine.Events;
|
|
|
|
namespace UnityEngine.UI
|
|
{
|
|
internal class ObjectPool<T> where T : new()
|
|
{
|
|
private readonly Stack<T> m_Stack = new Stack<T>();
|
|
|
|
private readonly UnityAction<T> m_ActionOnGet;
|
|
|
|
private readonly UnityAction<T> m_ActionOnRelease;
|
|
|
|
public int countAll { get; private set; }
|
|
|
|
public int countActive
|
|
{
|
|
get
|
|
{
|
|
return countAll - countInactive;
|
|
}
|
|
}
|
|
|
|
public int countInactive
|
|
{
|
|
get
|
|
{
|
|
return m_Stack.Count;
|
|
}
|
|
}
|
|
|
|
public ObjectPool(UnityAction<T> actionOnGet, UnityAction<T> actionOnRelease)
|
|
{
|
|
m_ActionOnGet = actionOnGet;
|
|
m_ActionOnRelease = actionOnRelease;
|
|
}
|
|
|
|
public T Get()
|
|
{
|
|
T val;
|
|
if (m_Stack.Count == 0)
|
|
{
|
|
val = new T();
|
|
countAll++;
|
|
}
|
|
else
|
|
{
|
|
val = m_Stack.Pop();
|
|
}
|
|
if (m_ActionOnGet != null)
|
|
{
|
|
m_ActionOnGet(val);
|
|
}
|
|
return val;
|
|
}
|
|
|
|
public void Release(T element)
|
|
{
|
|
if (m_Stack.Count > 0 && object.ReferenceEquals(m_Stack.Peek(), element))
|
|
{
|
|
Debug.LogError("Internal error. Trying to destroy object that is already released to pool.");
|
|
}
|
|
if (m_ActionOnRelease != null)
|
|
{
|
|
m_ActionOnRelease(element);
|
|
}
|
|
m_Stack.Push(element);
|
|
}
|
|
}
|
|
}
|