Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Threading;
- using Cysharp.Threading.Tasks;
- using Game.CameraLogic.Animals;
- using Game.Characteristics;
- using Game.Extensions;
- using UniRx;
- using UnityEngine;
- using IAction = Game.UtilityAI.Actions.IAction;
- namespace Game.UtilityAI
- {
- [RequireComponent(typeof(Animal))]
- public class AnimalUtilityAI : MonoBehaviour
- {
- private IUtilityAction[] _actions;
- private INeed[] _needs;
- [SerializeField] private Game.Infrastructure.Logger _logger;
- [SerializeField] private Animal _animal;
- private CancellationTokenSource _cancellationTokenSource;
- private void OnValidate()
- {
- _animal ??= GetComponent<Animal>();
- }
- private void Awake()
- {
- _needs = GetComponents<INeed>();
- _actions = GetComponents<IUtilityAction>();
- _cancellationTokenSource = new CancellationTokenSource();
- }
- private async void Start()
- {
- _animal
- .SubscribeOnDead(OnDead)
- .AddTo(this);
- await Run();
- }
- private void OnDead(Stat _)
- {
- enabled = false;
- Debug.Log("Animal is dead");
- CancelCurrentTask();
- }
- private async UniTask Run()
- {
- while (enabled)
- await ExecuteBestAction();
- }
- private void Update()
- {
- foreach(INeed need in _needs)
- need.Increase();
- }
- private async UniTask ExecuteBestAction()
- {
- IAction bestAction = GetBestAction();
- await bestAction.Execute(_cancellationTokenSource.Token);
- }
- [ContextMenu("Cancel current task")]
- private void CancelCurrentTask() =>
- _cancellationTokenSource.Cancel();
- private IAction GetBestAction()
- {
- float bestUtility = float.MinValue;
- IAction bestAction = null;
- foreach(IUtilityAction action in _actions)
- {
- float utility = action.GetUtility();
- bool isNotBest = utility < bestUtility;
- if (isNotBest)
- continue;
- bestUtility = utility;
- bestAction = action;
- }
- _logger.Log($"Best action is {bestAction.GetType().Name} with utility {bestUtility}");
- return bestAction;
- }
- private void OnDestroy()
- {
- CancelCurrentTask();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement