summaryrefslogtreecommitdiff
path: root/Assets/uGUI-2017.1/UnityEngine.UI/UI/Core/Utility/ObjectPool.cs
diff options
context:
space:
mode:
authorchai <chaifix@163.com>2021-05-08 23:15:13 +0800
committerchai <chaifix@163.com>2021-05-08 23:15:13 +0800
commitd07e14add74e017b52ab2371efeea1aa4ea10ced (patch)
treeefd07869326e4c428f5bfe43fad0c2583d32a401 /Assets/uGUI-2017.1/UnityEngine.UI/UI/Core/Utility/ObjectPool.cs
+init
Diffstat (limited to 'Assets/uGUI-2017.1/UnityEngine.UI/UI/Core/Utility/ObjectPool.cs')
-rw-r--r--Assets/uGUI-2017.1/UnityEngine.UI/UI/Core/Utility/ObjectPool.cs48
1 files changed, 48 insertions, 0 deletions
diff --git a/Assets/uGUI-2017.1/UnityEngine.UI/UI/Core/Utility/ObjectPool.cs b/Assets/uGUI-2017.1/UnityEngine.UI/UI/Core/Utility/ObjectPool.cs
new file mode 100644
index 0000000..b506d80
--- /dev/null
+++ b/Assets/uGUI-2017.1/UnityEngine.UI/UI/Core/Utility/ObjectPool.cs
@@ -0,0 +1,48 @@
+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 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);
+ }
+ }
+}