BITFALL/Assets/BITKit/Unity/Scripts/Entity/Components/Health/AutoRespawnComponent.cs

52 lines
1.2 KiB
C#
Raw Normal View History

2023-10-25 17:26:42 +08:00
using System;
2023-08-12 01:43:24 +08:00
using System.Collections;
using System.Collections.Generic;
2023-10-25 17:26:42 +08:00
using System.Threading;
using System.Threading.Tasks;
2023-08-12 01:43:24 +08:00
using BITKit.Entities;
using UnityEngine;
namespace BITKit
{
2023-10-30 01:25:53 +08:00
public class AutoRespawnBehavior : EntityBehavior,IAction
2023-08-12 01:43:24 +08:00
{
[SerializeField] private IntervalUpdate respawnInterval;
private bool requestRespawn;
2023-10-20 19:31:12 +08:00
[Inject] private IHealth _health;
2023-10-25 17:26:42 +08:00
private int _initialHp;
private CancellationTokenSource _cancellationTokenSource;
2023-08-12 01:43:24 +08:00
public override void OnAwake()
{
2023-10-25 17:26:42 +08:00
_initialHp=_health.HealthPoint;
2023-10-20 19:31:12 +08:00
_health.OnSetAlive += OnSetAlive;
2023-08-12 01:43:24 +08:00
}
2023-10-25 17:26:42 +08:00
private async void OnSetAlive(bool alive)
2023-08-12 01:43:24 +08:00
{
if (alive)
{
2023-10-25 17:26:42 +08:00
_cancellationTokenSource?.Cancel();
2023-08-12 01:43:24 +08:00
}
else
{
2023-10-25 17:26:42 +08:00
_cancellationTokenSource?.Cancel();
_cancellationTokenSource = new CancellationTokenSource();
try
{
await Task.Delay(TimeSpan.FromSeconds(respawnInterval.Interval), _cancellationTokenSource.Token);
destroyCancellationToken.ThrowIfCancellationRequested();
Execute();
}
2023-10-29 15:27:13 +08:00
catch(MissingReferenceException){}
2023-10-25 17:26:42 +08:00
catch (OperationCanceledException){}
2023-08-12 01:43:24 +08:00
}
}
public void Execute()
{
2023-10-25 17:26:42 +08:00
if (_health.IsAlive is false)
_health.HealthPoint = _initialHp;
2023-08-12 01:43:24 +08:00
}
}
}