using System; using System.Collections.Generic; using System.Linq; using Lean.Pool; using Sirenix.OdinInspector; using UnityEngine; namespace SLSUtilities.LeanPoolAssistance { public class PooledObject : SerializedMonoBehaviour, IPoolable { [Tooltip("是否在生成后定时自动回收")] public bool isAutoDespawn = true; [ShowIf("isAutoDespawn")][Tooltip("自动回收时间")] public float autoDespawnTime = 1; [ShowIf("isAutoDespawn")][Tooltip("自动回收计时器")][ReadOnly][HideInEditorMode] public float despawnTimer; private List children; protected bool spawnExecuted = false; [HideInInspector] public Action onSpawnAction; [HideInInspector] public Action onDespawnAction; public virtual void OnSpawn() { if (spawnExecuted) { return; } spawnExecuted = true; despawnTimer = 0; onSpawnAction?.Invoke(); children = GetComponentsInChildren().ToList(); children.Remove(this); children.ForEach(child => child.OnSpawn()); } protected virtual void Update() { UpdateTimer(Time.deltaTime); } protected virtual void UpdateTimer(float deltaTime) { if (!isAutoDespawn) { return; } despawnTimer += deltaTime; if (despawnTimer >= autoDespawnTime) { LeanPool.Despawn(gameObject); } } public virtual void OnDespawn() { spawnExecuted = false; onDespawnAction?.Invoke(); children.ForEach(child => child.OnDespawn()); } } }