using System; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace BaseGames.Core.Pool { /// /// 可池化对象组件,挂在每个可池化 Prefab 的根节点上。 /// 实现 的子类可覆盖 OnSpawn/OnDespawn。 /// public class PooledObject : MonoBehaviour { public string AddressKey { get; private set; } private GlobalObjectPool _pool; // 组件缓存(避免反复 GetComponent) private readonly Dictionary _componentCache = new(); public void Setup(string key, GlobalObjectPool pool) { AddressKey = key; _pool = pool; } public virtual void OnSpawn() { } public virtual void OnDespawn(){ } // ── 归还 API ────────────────────────────────────────────────────── /// 立即归还到对象池。 public void ReturnToPool() => _pool?.Despawn(AddressKey, this); /// 延迟 delay 秒后归还。 public void ReturnToPoolDelayed(float delay) => StartCoroutine(DelayedReturn(delay)); /// /// 由 GlobalObjectPool LRU 回收触发,不应由业务代码直接调用。 /// internal void ForceReturnToPool() { OnDespawn(); gameObject.SetActive(false); } // ── 组件缓存 ────────────────────────────────────────────────────── /// 从缓存获取 Component,首次调用才执行 GetComponent。 public T GetComponentCached() where T : Component { if (!_componentCache.TryGetValue(typeof(T), out var cached)) _componentCache[typeof(T)] = cached = GetComponent(); return (T)cached; } private IEnumerator DelayedReturn(float delay) { yield return new WaitForSeconds(delay); ReturnToPool(); } } /// /// 可选接口:若池化对象需要在 Spawn/Despawn 时执行额外逻辑, /// 由 PooledObject 子类或同 GameObject 上的其他 MonoBehaviour 实现, /// 并在 PooledObject.OnSpawn/OnDespawn 中手动驱动。 /// public interface IPoolable { void OnSpawn(); void OnDespawn(); } }