Unity 框架

ObjectPool.cs 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace TFramework
  5. {
  6. public class ObjectPool
  7. {
  8. private GameObject _objTemplate;
  9. private Queue<GameObject> _objPool;
  10. private int _maxCount;
  11. private TAction<GameObject> OnTakeOut;
  12. private TAction<GameObject> OnRecycle;
  13. List<Component> _initComponents = new List<Component>();
  14. public ObjectPool(GameObject objTemplate, int maxCount, TAction<GameObject> takeOutEvent, TAction<GameObject> recycleEvent)
  15. {
  16. _objTemplate = objTemplate;
  17. _maxCount = maxCount;
  18. _objPool = new Queue<GameObject>(_maxCount);
  19. OnTakeOut = takeOutEvent;
  20. OnRecycle = recycleEvent;
  21. }
  22. public int Count => _objPool.Count;
  23. /// <summary>
  24. /// È¡³ö¶ÔÏó
  25. /// </summary>
  26. /// <returns></returns>
  27. public GameObject TakeOutObj()
  28. {
  29. GameObject obj;
  30. if (Count > 0)
  31. obj = _objPool.Dequeue();
  32. else
  33. obj = GameObject.Instantiate(_objTemplate);
  34. obj.SetActive(true);
  35. OnTakeOut?.Invoke(obj);
  36. return obj;
  37. }
  38. /// <summary>
  39. /// »ØÊÕ¶ÔÏó
  40. /// </summary>
  41. /// <param name="obj"></param>
  42. public void RecycleObj(GameObject obj)
  43. {
  44. obj.SetActive(false);
  45. _initComponents.Clear();
  46. _initComponents.AddRange(obj.GetComponents<Component>());
  47. foreach (var template in _objTemplate.GetComponents<Component>())
  48. {
  49. for (int i = 0; i < _initComponents.Count; i++)
  50. {
  51. if (template.GetType().Equals(_initComponents[i].GetType()))
  52. {
  53. _initComponents[i] = template;
  54. _initComponents.Remove(_initComponents[i]);
  55. break;
  56. }
  57. }
  58. }
  59. OnRecycle?.Invoke(obj);
  60. if (Count >= _maxCount)
  61. GameObject.Destroy(obj);
  62. else
  63. _objPool.Enqueue(obj);
  64. }
  65. public void Clear()
  66. {
  67. while (Count > 0)
  68. {
  69. GameObject.Destroy(_objPool.Dequeue());
  70. }
  71. }
  72. }
  73. }