TMP_ObjectPool.cs 1.5 KB

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