From cb893e1e5e4820cb800836cf6b8a79a1cd986cdc Mon Sep 17 00:00:00 2001 From: chai Date: Thu, 22 Jul 2021 18:34:47 +0800 Subject: *misc --- Assets/Scripts/Utils/ListPool.cs | 65 +++++++++++++++++++++++++++++++++++ Assets/Scripts/Utils/ListPool.cs.meta | 11 ++++++ 2 files changed, 76 insertions(+) create mode 100644 Assets/Scripts/Utils/ListPool.cs create mode 100644 Assets/Scripts/Utils/ListPool.cs.meta (limited to 'Assets/Scripts/Utils') 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 +{ + public static List Get() + { + return ListPool.m_ListPool.Get(); + } + + public static void Release(List toRelease) + { + ListPool.m_ListPool.Release(toRelease); + } + + private static readonly ObjectPool> m_ListPool = new ObjectPool>(null, delegate (List l) + { + l.Clear(); + }); +} + +internal class ObjectPool where T : new() +{ + private readonly Stack m_Stack = new Stack(); + private readonly UnityAction m_ActionOnGet; + private readonly UnityAction 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 actionOnGet, UnityAction 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: -- cgit v1.1-26-g67d0