ObjectPool.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /************************************************/
  2. /* */
  3. /* Copyright (c) 2018 - 2021 monitor1394 */
  4. /* https://github.com/monitor1394 */
  5. /* */
  6. /************************************************/
  7. using System.Collections.Generic;
  8. using UnityEngine;
  9. using UnityEngine.Events;
  10. namespace XCharts
  11. {
  12. internal class ObjectPool<T> where T : new()
  13. {
  14. private readonly Stack<T> m_Stack = new Stack<T>();
  15. private readonly UnityAction<T> m_ActionOnGet;
  16. private readonly UnityAction<T> m_ActionOnRelease;
  17. public int countAll { get; private set; }
  18. public int countActive { get { return countAll - countInactive; } }
  19. public int countInactive { get { return m_Stack.Count; } }
  20. public ObjectPool(UnityAction<T> actionOnGet, UnityAction<T> actionOnRelease)
  21. {
  22. m_ActionOnGet = actionOnGet;
  23. m_ActionOnRelease = actionOnRelease;
  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. public void Release(T element)
  42. {
  43. if (m_Stack.Count > 0 && ReferenceEquals(m_Stack.Peek(), element))
  44. Debug.LogError("Internal error. Trying to destroy object that is already released to pool.");
  45. if (m_ActionOnRelease != null)
  46. m_ActionOnRelease(element);
  47. m_Stack.Push(element);
  48. }
  49. public void ClearAll()
  50. {
  51. m_Stack.Clear();
  52. }
  53. }
  54. }