|
- using System;
- using System.Collections.Generic;
- using UnityEngine;
-
- namespace CIG
- {
- public class ObjectPool : MonoBehaviour
- {
- private void Awake()
- {
- this._availablePool = new List<GameObject>(this._initialPoolCount);
- this._claimedPool = new List<GameObject>(this._initialPoolCount);
- for (int i = 0; i < this._initialPoolCount; i++)
- {
- GameObject gameObject = UnityEngine.Object.Instantiate<GameObject>(this._prefab, base.transform, false);
- gameObject.SetActive(false);
- this._availablePool.Add(gameObject);
- }
- }
-
- public T Pop<T>(Transform parent) where T : MonoBehaviour
- {
- GameObject gameObject = this.Pop(base.transform);
- return gameObject.GetComponent<T>();
- }
-
- public GameObject Pop(Transform parent)
- {
- GameObject gameObject;
- if (this._availablePool.Count == 0)
- {
- UnityEngine.Debug.LogWarning("Failed to pop an instance from the Pool, no more instances available. - Instantiating a new one !");
- gameObject = UnityEngine.Object.Instantiate<GameObject>(this._prefab, base.transform, false);
- }
- else
- {
- gameObject = this._availablePool[0];
- this._availablePool.RemoveAt(0);
- }
- this._claimedPool.Add(gameObject);
- gameObject.SetActive(true);
- gameObject.transform.SetParent(parent, false);
- return gameObject;
- }
-
- public void Push(List<GameObject> instances)
- {
- int count = instances.Count;
- for (int i = 0; i < count; i++)
- {
- this.Push(instances[i]);
- }
- }
-
- public void Push(GameObject instance)
- {
- if (!this._claimedPool.Remove(instance))
- {
- if (!this._availablePool.Contains(instance))
- {
- UnityEngine.Debug.LogWarningFormat("Failed to push '{0}' back to the pool, it doesn't belong to this ObjectPool!", new object[]
- {
- instance.name
- });
- }
- else
- {
- UnityEngine.Debug.LogWarningFormat("Failed to push '{0}' back to the pool, it was never popped!", new object[]
- {
- instance.name
- });
- }
- return;
- }
- instance.transform.SetParent(base.transform, false);
- instance.SetActive(false);
- this._availablePool.Add(instance);
- }
-
- public int AvailableInstances
- {
- get
- {
- return this._availablePool.Count;
- }
- }
-
- public int ClaimedInstances
- {
- get
- {
- return this._claimedPool.Count;
- }
- }
-
- public int TotalInstances
- {
- get
- {
- return this.AvailableInstances + this.ClaimedInstances;
- }
- }
-
- [SerializeField]
- private GameObject _prefab;
-
- [SerializeField]
- private int _initialPoolCount;
-
- private List<GameObject> _availablePool;
-
- private List<GameObject> _claimedPool;
- }
- }
|