Files
Cielonos/Assets/Scripts/SLSUtilities/LeanPoolAssistance/PooledObject.cs

72 lines
1.9 KiB
C#
Raw Normal View History

2025-12-17 04:19:38 -05:00
using System;
2025-11-25 08:19:33 -05:00
using System.Collections.Generic;
using System.Linq;
using Lean.Pool;
using Sirenix.OdinInspector;
using UnityEngine;
2026-02-13 09:22:11 -05:00
namespace SLSUtilities.LeanPoolAssistance
2025-11-25 08:19:33 -05:00
{
2025-12-08 05:27:53 -05:00
public class PooledObject : SerializedMonoBehaviour, IPoolable
2025-11-25 08:19:33 -05:00
{
[Tooltip("是否在生成后定时自动回收")]
public bool isAutoDespawn = true;
[ShowIf("isAutoDespawn")][Tooltip("自动回收时间")]
public float autoDespawnTime = 1;
2025-12-17 04:19:38 -05:00
[ShowIf("isAutoDespawn")][Tooltip("自动回收计时器")][ReadOnly][HideInEditorMode]
public float despawnTimer;
2025-11-25 08:19:33 -05:00
private List<IPoolable> children;
2025-12-17 04:19:38 -05:00
protected bool spawnExecuted = false;
2025-11-25 08:19:33 -05:00
2026-02-13 09:22:11 -05:00
[HideInInspector]
2025-12-24 16:58:51 -05:00
public Action onSpawnAction;
2026-02-13 09:22:11 -05:00
[HideInInspector]
2025-12-24 16:58:51 -05:00
public Action onDespawnAction;
2025-12-17 04:19:38 -05:00
public virtual void OnSpawn()
2025-11-25 08:19:33 -05:00
{
if (spawnExecuted)
{
return;
}
spawnExecuted = true;
2025-12-17 04:19:38 -05:00
despawnTimer = 0;
2025-12-24 16:58:51 -05:00
onSpawnAction?.Invoke();
2025-11-25 08:19:33 -05:00
children = GetComponentsInChildren<IPoolable>().ToList();
children.Remove(this);
children.ForEach(child => child.OnSpawn());
2025-12-17 04:19:38 -05:00
}
protected virtual void Update()
{
UpdateTimer(Time.deltaTime);
}
protected virtual void UpdateTimer(float deltaTime)
{
if (!isAutoDespawn)
{
return;
}
despawnTimer += deltaTime;
if (despawnTimer >= autoDespawnTime)
2025-11-25 08:19:33 -05:00
{
2025-12-17 04:19:38 -05:00
LeanPool.Despawn(gameObject);
2025-11-25 08:19:33 -05:00
}
}
2025-12-24 16:58:51 -05:00
public virtual void OnDespawn()
2025-11-25 08:19:33 -05:00
{
spawnExecuted = false;
2025-12-24 16:58:51 -05:00
onDespawnAction?.Invoke();
2025-11-25 08:19:33 -05:00
children.ForEach(child => child.OnDespawn());
}
}
}