A game about forced loneliness, made by TACStudios
at master 51 lines 1.5 kB view raw
1using System.Collections.Generic; 2using UnityEngine; 3using UnityEngine.Events; 4 5 6namespace TMPro 7{ 8 9 internal class TMP_ObjectPool<T> where T : new() 10 { 11 private readonly Stack<T> m_Stack = new Stack<T>(); 12 private readonly UnityAction<T> m_ActionOnGet; 13 private readonly UnityAction<T> m_ActionOnRelease; 14 15 public int countAll { get; private set; } 16 public int countActive { get { return countAll - countInactive; } } 17 public int countInactive { get { return m_Stack.Count; } } 18 19 public TMP_ObjectPool(UnityAction<T> actionOnGet, UnityAction<T> actionOnRelease) 20 { 21 m_ActionOnGet = actionOnGet; 22 m_ActionOnRelease = actionOnRelease; 23 } 24 25 public T Get() 26 { 27 T element; 28 if (m_Stack.Count == 0) 29 { 30 element = new T(); 31 countAll++; 32 } 33 else 34 { 35 element = m_Stack.Pop(); 36 } 37 if (m_ActionOnGet != null) 38 m_ActionOnGet(element); 39 return element; 40 } 41 42 public void Release(T element) 43 { 44 if (m_Stack.Count > 0 && ReferenceEquals(m_Stack.Peek(), element)) 45 Debug.LogError("Internal error. Trying to destroy object that is already released to pool."); 46 if (m_ActionOnRelease != null) 47 m_ActionOnRelease(element); 48 m_Stack.Push(element); 49 } 50 } 51}