ObjectPool.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace HyperlinkText
  5. {
  6. public class ObjectPool<T> where T : new()
  7. {
  8. public ObjectPool(Action<T> onGet, Action<T> onRelease)
  9. {
  10. this.m_OnGet = onGet;
  11. this.m_OnRelease = onRelease;
  12. }
  13. public int CountAll { get; set; }
  14. public int CountActive
  15. {
  16. get
  17. {
  18. return this.CountAll - this.CountInactive;
  19. }
  20. }
  21. public int CountInactive
  22. {
  23. get
  24. {
  25. return this.m_Stack.Count;
  26. }
  27. }
  28. public T Get()
  29. {
  30. T t;
  31. if (this.m_Stack.Count == 0)
  32. {
  33. t = Activator.CreateInstance<T>();
  34. this.CountAll++;
  35. }
  36. else
  37. {
  38. t = this.m_Stack.Pop();
  39. }
  40. if (this.m_OnGet != null)
  41. {
  42. this.m_OnGet(t);
  43. }
  44. return t;
  45. }
  46. public void Release(T item)
  47. {
  48. if (this.m_Stack.Count > 0)
  49. {
  50. T t = this.m_Stack.Peek();
  51. if (t.Equals(item))
  52. {
  53. Debug.LogError("Internal error. Trying to destroy object that is already released to pool.");
  54. }
  55. }
  56. if (this.m_OnRelease != null)
  57. {
  58. this.m_OnRelease(item);
  59. }
  60. this.m_Stack.Push(item);
  61. }
  62. private readonly Stack<T> m_Stack = new Stack<T>();
  63. private readonly Action<T> m_OnGet;
  64. private readonly Action<T> m_OnRelease;
  65. }
  66. }