diff options
author | chai <215380520@qq.com> | 2023-05-16 16:03:51 +0800 |
---|---|---|
committer | chai <215380520@qq.com> | 2023-05-16 16:03:51 +0800 |
commit | 2afbb545027568fccc85853e18af02a7c6b2929e (patch) | |
tree | 3827873af133fe9f81041e4babbfd0d54a53f9d1 /WorldlineKeepers/Assets/Scripts/Tools/ObjectPool.cs | |
parent | 88f739ea0f3440152082f34707e79328a71aabed (diff) |
*misc
Diffstat (limited to 'WorldlineKeepers/Assets/Scripts/Tools/ObjectPool.cs')
-rw-r--r-- | WorldlineKeepers/Assets/Scripts/Tools/ObjectPool.cs | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/WorldlineKeepers/Assets/Scripts/Tools/ObjectPool.cs b/WorldlineKeepers/Assets/Scripts/Tools/ObjectPool.cs new file mode 100644 index 0000000..ac18a9a --- /dev/null +++ b/WorldlineKeepers/Assets/Scripts/Tools/ObjectPool.cs @@ -0,0 +1,51 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.Events; + +namespace WK +{ + 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 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); + } + } + +}
\ No newline at end of file |