2021-01-11 08:54:28 +08:00
|
|
|
/************************************************/
|
|
|
|
|
/* */
|
|
|
|
|
/* Copyright (c) 2018 - 2021 monitor1394 */
|
|
|
|
|
/* https://github.com/monitor1394 */
|
|
|
|
|
/* */
|
|
|
|
|
/************************************************/
|
2019-10-22 04:09:04 +08:00
|
|
|
|
2019-08-15 21:44:30 +08:00
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using UnityEngine;
|
|
|
|
|
using UnityEngine.Events;
|
|
|
|
|
|
|
|
|
|
namespace XCharts
|
|
|
|
|
{
|
2019-11-02 08:24:37 +08:00
|
|
|
internal class ObjectPool<T> where T : new()
|
2019-08-15 21:44:30 +08:00
|
|
|
{
|
|
|
|
|
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 element;
|
|
|
|
|
if (m_Stack.Count == 0)
|
|
|
|
|
{
|
|
|
|
|
element = new T();
|
|
|
|
|
countAll++;
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
element = m_Stack.Pop();
|
|
|
|
|
}
|
|
|
|
|
if (m_ActionOnGet != null)
|
|
|
|
|
m_ActionOnGet(element);
|
|
|
|
|
return element;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void Release(T element)
|
|
|
|
|
{
|
|
|
|
|
if (m_Stack.Count > 0 && 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);
|
|
|
|
|
}
|
2020-05-13 09:54:40 +08:00
|
|
|
|
|
|
|
|
public void ClearAll()
|
|
|
|
|
{
|
|
|
|
|
m_Stack.Clear();
|
|
|
|
|
}
|
2019-08-15 21:44:30 +08:00
|
|
|
}
|
|
|
|
|
}
|