namespace UIWidgets { using System; using System.Collections.Generic; using UnityEngine; /// /// Component pool. /// /// Type of object. public class ComponentPool : MonoBehaviour where T : MonoBehaviour { /// /// The cache. /// protected static Stack Cache = new Stack(); /// /// Clones or take from cache the object original and returns the clone. /// /// New object instance. public T Instance() { T instance; if (Cache.Count == 0) { instance = Instantiate(this) as T; } else { do { instance = (Cache.Count > 0) ? Cache.Pop() : Instantiate(this) as T; } while (instance == null); } instance.transform.SetParent(transform.parent, false); instance.gameObject.SetActive(true); return instance; } /// /// Clones or take from cache the object original and returns the clone. /// /// Parent. /// New object instance. public T Instance(Transform parent) { var instance = Instance(); instance.transform.SetParent(parent, false); return instance; } /// /// Return current object to cache. /// public void Free() { Cache.Push(this as T); gameObject.SetActive(false); } /// /// Return current object to cache. /// /// Parent. public void Free(Transform parent) { Free(); transform.SetParent(parent, false); } /// /// Apply action for each object in cache. /// /// Action. public void ForEachCache(Action action) { foreach (var c in Cache) { action(c); } } } }