BITFALL/Assets/Artists/Scripts/Scenes/EvacuateArea.cs

70 lines
1.6 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BITKit;
using BITKit.Entities;
using BITKit.Entities.Player;
using BITKit.Events;
using BITKit.Game;
using BITKit.Sensors;
using Cysharp.Threading.Tasks;
using UnityEngine;
namespace BITFALL.Scenes
{
public class EvacuateArea : MonoBehaviour,IAction
{
[SerializeReference, SubclassSelector] private ISensor sensor;
[SerializeReference,SubclassSelector] private IGameService gameService;
[SerializeField] private Optional<float> stopGameWhenEvacuated = new();
[SerializeField] private UnityEvent onEvacuated;
private CancellationToken _cancellationToken;
private void Start()
{
_cancellationToken = this.GetCancellationTokenOnDestroy();
}
public async void EvacuateScopedPlayer()
{
var players = sensor.Get()
.FirstOrDefault(x=> x.TryGetComponent<IEntityPlayerComponent>(out _));
if(players is null)return;
var player = players.GetComponent<IEntityPlayerComponent>();
Destroy(players.gameObject);
if (!stopGameWhenEvacuated.Allow)
{
onEvacuated?.Invoke();
return;
}
BIT4Log.Log<EvacuateArea>($"玩家已撤离,战局将在{stopGameWhenEvacuated.Value}秒后停止");
try
{
await Task.Delay(TimeSpan.FromSeconds(stopGameWhenEvacuated.Value), _cancellationToken);
}
catch (OperationCanceledException)
{
return;
}
BIT4Log.Log<EvacuateArea>($"玩家已撤离,战局已停止");
gameService.Stop();
onEvacuated?.Invoke();
}
void IAction.Execute() => EvacuateScopedPlayer();
}
}