using UnityEngine; namespace Core.Utilities { /// /// Class that is to be pooled /// public class Poolable : MonoBehaviour { /// /// Number of poolables the pool will initialize /// public int initialPoolCapacity = 10; /// /// Pool that this poolable belongs to /// public Pool pool; /// /// Repool this instance, and move us under the poolmanager /// protected virtual void Repool() { transform.SetParent(PoolManager.instance.transform, false); pool.Return(this); } /// gameObject /// Pool the object if possible, otherwise destroy it /// /// GameObject attempting to pool public static void TryPool(GameObject gameObject) { var poolable = gameObject.GetComponent(); if (poolable != null && poolable.pool != null && PoolManager.instanceExists) { poolable.Repool(); } else { Destroy(gameObject); } } /// /// If the prefab is poolable returns a pooled object otherwise instantiates a new object /// /// Prefab of object required /// Component type /// The pooled or instantiated component public static T TryGetPoolable(GameObject prefab) where T : Component { var poolable = prefab.GetComponent(); T instance = poolable != null && PoolManager.instanceExists ? PoolManager.instance.GetPoolable(poolable).GetComponent() : Instantiate(prefab).GetComponent(); return instance; } /// /// If the prefab is poolable returns a pooled object otherwise instantiates a new object /// /// Prefab of object required /// The pooled or instantiated gameObject public static GameObject TryGetPoolable(GameObject prefab) { var poolable = prefab.GetComponent(); GameObject instance = poolable != null && PoolManager.instanceExists ? PoolManager.instance.GetPoolable(poolable).gameObject : Instantiate(prefab); return instance; } } }