ObjectPool.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. public class ObjectPool
  6. {
  7. public IEnumerator Init(GameObject prefab, GameObject parent, int size, int maxSize)
  8. {
  9. this.queue = new Queue<GameObject>();
  10. this.prefab = prefab;
  11. this.parent = parent;
  12. this.maxSize = maxSize;
  13. if (prefab != null)
  14. {
  15. for (int i = 0; i < size; i++)
  16. {
  17. GameObject temp = this.InsertObject();
  18. temp.SetActive(true);
  19. temp.transform.position = new Vector3(-1000f, 0f, 0f);
  20. yield return null;
  21. temp.SetActive(false);
  22. }
  23. }
  24. yield break;
  25. }
  26. public GameObject GetObject()
  27. {
  28. if (this.queue.Count == 0)
  29. {
  30. return this.InsertObject();
  31. }
  32. if (this.queue.Peek() == null)
  33. {
  34. this.queue.Dequeue();
  35. return this.InsertObject();
  36. }
  37. if (this.queue.Peek().activeSelf && this.queue.Count < this.maxSize)
  38. {
  39. return this.InsertObject();
  40. }
  41. GameObject gameObject = this.queue.Dequeue();
  42. this.queue.Enqueue(gameObject);
  43. if (this.queue.Count >= this.maxSize)
  44. {
  45. gameObject.SetActive(false);
  46. }
  47. return gameObject;
  48. }
  49. public GameObject InsertObject()
  50. {
  51. GameObject gameObject = UnityEngine.Object.Instantiate<GameObject>(this.prefab, Vector3.zero, Quaternion.identity);
  52. gameObject.name = this.prefab.name;
  53. if (this.parent != null)
  54. {
  55. gameObject.transform.parent = this.parent.transform;
  56. }
  57. gameObject.SetActive(false);
  58. this.queue.Enqueue(gameObject);
  59. return gameObject;
  60. }
  61. public Queue<GameObject> queue;
  62. public GameObject prefab;
  63. public GameObject parent;
  64. public int maxSize = 10;
  65. }