|
| 1 | +using System.Collections; |
| 2 | +using System.Collections.Generic; |
| 3 | +using UnityEngine; |
| 4 | + |
| 5 | +public abstract class GenericObjectPool<T> : MonoBehaviour where T : Component |
| 6 | +{ |
| 7 | + #region Fields |
| 8 | + [SerializeField] |
| 9 | + private T prefab; |
| 10 | + |
| 11 | + private Queue<T> pooledObjects = new Queue<T>(); |
| 12 | + #endregion |
| 13 | + |
| 14 | + #region Singleton |
| 15 | + //Singleton Instantiation |
| 16 | + public static GenericObjectPool<T> Instance { get; private set; } |
| 17 | + |
| 18 | + private void Awake() |
| 19 | + { |
| 20 | + if (Instance != null && Instance != this) |
| 21 | + Destroy(this.gameObject); |
| 22 | + else |
| 23 | + Instance = this; |
| 24 | + |
| 25 | + DontDestroyOnLoad(this); |
| 26 | + } |
| 27 | + |
| 28 | + |
| 29 | + #endregion |
| 30 | + |
| 31 | + #region Public Pool Accessing |
| 32 | + /// <summary> |
| 33 | + /// Gets Object of Type T from Pool |
| 34 | + /// </summary> |
| 35 | + /// <returns>Object of Type T</returns> |
| 36 | + public T Get() |
| 37 | + { |
| 38 | + if (pooledObjects.Count == 0) |
| 39 | + AddObjects(1); |
| 40 | + |
| 41 | + return pooledObjects.Dequeue(); |
| 42 | + } |
| 43 | + |
| 44 | + /// <summary> |
| 45 | + /// Recycles object that was being used back into the active pool |
| 46 | + /// </summary> |
| 47 | + /// <param name="objectToSet"></param> |
| 48 | + public void Recycle(T objectToSet) |
| 49 | + { |
| 50 | + objectToSet.gameObject.SetActive(false); |
| 51 | + pooledObjects.Enqueue(objectToSet); |
| 52 | + } |
| 53 | + #endregion |
| 54 | + |
| 55 | + #region Pool Modifying |
| 56 | + /// <summary> |
| 57 | + /// |
| 58 | + /// </summary> |
| 59 | + /// <param name="count"></param> |
| 60 | + private void AddObjects(int count) |
| 61 | + { |
| 62 | + for (int i = 0; i < count; i++) |
| 63 | + { |
| 64 | + var newObject = Instantiate(prefab, Vector3.zero, Quaternion.identity, transform); |
| 65 | + AddPoolReference(newObject); |
| 66 | + Recycle(newObject); |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + /// <summary> |
| 71 | + /// Adds reference to the pooled object Via Interface |
| 72 | + /// </summary> |
| 73 | + /// <param name="objectToAddReference"></param> |
| 74 | + public abstract void AddPoolReference(T objectToAddReference); |
| 75 | + #endregion |
| 76 | +} |
0 commit comments