GameObjectPool.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class GameObjectPool<T> where T : class, new()
  5. {
  6. private Stack<T> m_GOStack;
  7. private int m_iMaxRecycledItem = 5;
  8. private float mLastUsedTime = 0f;
  9. public int Count
  10. {
  11. get { return m_GOStack.Count; }
  12. }
  13. public GameObjectPool()
  14. {
  15. m_GOStack = new Stack<T>();
  16. mLastUsedTime = Time.time + 20f;
  17. }
  18. public void SetMaxCacheNum(int num)
  19. {
  20. this.m_iMaxRecycledItem = num;
  21. }
  22. public T Spawn()
  23. {
  24. if (m_GOStack.Count > 0)
  25. {
  26. T t = m_GOStack.Pop();
  27. mLastUsedTime = Time.time + 20f;
  28. return t;
  29. }
  30. return null;
  31. }
  32. public void Recycle(T obj)
  33. {
  34. if (obj != null)
  35. {
  36. if (m_GOStack.Count > m_iMaxRecycledItem)
  37. {
  38. GameObject.Destroy(obj as GameObject);
  39. return;
  40. }
  41. m_GOStack.Push(obj);
  42. }
  43. }
  44. public void Dispose()
  45. {
  46. if(m_GOStack.Count > 0)
  47. {
  48. while(true)
  49. {
  50. T t = Spawn();
  51. if (t != null)
  52. {
  53. GameObject.Destroy(t as GameObject);
  54. }
  55. else
  56. return;
  57. }
  58. }
  59. }
  60. public bool NeedRelease()
  61. {
  62. return mLastUsedTime > Time.time;
  63. }
  64. }