diff options
Diffstat (limited to 'Assets/Scripts/Utils')
-rw-r--r-- | Assets/Scripts/Utils/ListPool.cs | 65 | ||||
-rw-r--r-- | Assets/Scripts/Utils/ListPool.cs.meta | 11 |
2 files changed, 76 insertions, 0 deletions
diff --git a/Assets/Scripts/Utils/ListPool.cs b/Assets/Scripts/Utils/ListPool.cs new file mode 100644 index 00000000..b9fbd2b8 --- /dev/null +++ b/Assets/Scripts/Utils/ListPool.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using UnityEngine;
+using UnityEngine.Events;
+
+public static class ListPool<T>
+{
+ public static List<T> Get()
+ {
+ return ListPool<T>.m_ListPool.Get();
+ }
+
+ public static void Release(List<T> toRelease)
+ {
+ ListPool<T>.m_ListPool.Release(toRelease);
+ }
+
+ private static readonly ObjectPool<List<T>> m_ListPool = new ObjectPool<List<T>>(null, delegate (List<T> l)
+ {
+ l.Clear();
+ });
+}
+
+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);
+ }
+}
\ No newline at end of file diff --git a/Assets/Scripts/Utils/ListPool.cs.meta b/Assets/Scripts/Utils/ListPool.cs.meta new file mode 100644 index 00000000..61b7dcc3 --- /dev/null +++ b/Assets/Scripts/Utils/ListPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 385194156796a3241a248d31172defe5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: |