using UnityEngine; using UnityEngine.Events; namespace MoreMountains.Tools { /// /// Add this class to an object that you expect to pool from an objectPooler. /// Note that these objects can't be destroyed by calling Destroy(), they'll just be set inactive (that's the whole point). /// [AddComponentMenu("More Mountains/Tools/Object Pool/MMPoolableObject")] public class MMPoolableObject : MMObjectBounds { [Header("Events")] public UnityEvent ExecuteOnEnable; public UnityEvent ExecuteOnDisable; public delegate void Events(); public event Events OnSpawnComplete; [Header("Poolable Object")] /// The life time, in seconds, of the object. If set to 0 it'll live forever, if set to any positive value it'll be set inactive after that time. public float LifeTime = 0f; /// /// Turns the instance inactive, in order to eventually reuse it. /// public virtual void Destroy() { gameObject.SetActive(false); } /// /// Called every frame /// protected virtual void Update() { } /// /// When the objects get enabled (usually after having been pooled from an ObjectPooler, we initiate its death countdown. /// protected virtual void OnEnable() { Size = GetBounds().extents * 2; if (LifeTime > 0f) { Invoke("Destroy", LifeTime); } ExecuteOnEnable?.Invoke(); } /// /// When the object gets disabled (maybe it got out of bounds), we cancel its programmed death /// protected virtual void OnDisable() { ExecuteOnDisable?.Invoke(); CancelInvoke(); } /// /// Triggers the on spawn complete event /// public virtual void TriggerOnSpawnComplete() { OnSpawnComplete?.Invoke(); } } }