暂无描述
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

ObjectPool.cs 1.7KB

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