ObjectPool.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /*
  2. * uGUI-Hypertext (https://github.com/setchi/uGUI-Hypertext)
  3. * Copyright (c) 2019 setchi
  4. * Licensed under MIT (https://github.com/setchi/uGUI-Hypertext/blob/master/LICENSE)
  5. */
  6. using System;
  7. using System.Collections.Generic;
  8. namespace Hypertext
  9. {
  10. public class ObjectPool<T> where T : new()
  11. {
  12. readonly Stack<T> stack = new Stack<T>();
  13. readonly Action<T> onGet;
  14. readonly Action<T> onRelease;
  15. public int CountAll { get; set; }
  16. public int CountActive => CountAll - CountInactive;
  17. public int CountInactive => stack.Count;
  18. public ObjectPool(Action<T> onGet, Action<T> onRelease)
  19. {
  20. this.onGet = onGet;
  21. this.onRelease = onRelease;
  22. }
  23. public T Get()
  24. {
  25. T element;
  26. if (stack.Count == 0)
  27. {
  28. element = new T();
  29. CountAll++;
  30. }
  31. else
  32. {
  33. element = stack.Pop();
  34. }
  35. onGet?.Invoke(element);
  36. return element;
  37. }
  38. public void Release(T element)
  39. {
  40. if (stack.Count > 0 && ReferenceEquals(stack.Peek(), element))
  41. {
  42. UnityEngine.Debug.LogError("Internal error. Trying to destroy object that is already released to pool.");
  43. }
  44. onRelease?.Invoke(element);
  45. stack.Push(element);
  46. }
  47. }
  48. }