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

52 lines
1.2 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using BITKit.Entities;
using UnityEngine;
namespace BITKit
{
public class AutoRespawnBehavior : EntityBehavior,IAction
{
[SerializeField] private IntervalUpdate respawnInterval;
private bool requestRespawn;
[Inject] private IHealth _health;
private int _initialHp;
private CancellationTokenSource _cancellationTokenSource;
public override void OnAwake()
{
_initialHp=_health.HealthPoint;
_health.OnSetAlive += OnSetAlive;
}
private async void OnSetAlive(bool alive)
{
if (alive)
{
_cancellationTokenSource?.Cancel();
}
else
{
_cancellationTokenSource?.Cancel();
_cancellationTokenSource = new CancellationTokenSource();
try
{
await Task.Delay(TimeSpan.FromSeconds(respawnInterval.Interval), _cancellationTokenSource.Token);
destroyCancellationToken.ThrowIfCancellationRequested();
Execute();
}
catch(MissingReferenceException){}
catch (OperationCanceledException){}
}
}
public void Execute()
{
if (_health.IsAlive is false)
_health.HealthPoint = _initialHp;
}
}
}