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; } } }