Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections.Generic;
- namespace AIScripts.UtilityAI
- {
- public interface IAction
- {
- void Execute();
- float GetUtility();
- }
- public class AnimalAI : MonoBehaviour
- {
- [SerializeField] private float _hunger;
- [SerializeField] private float _thirst;
- [SerializeField] private float _fatigue;
- private List<IAction> _actions;
- private void Start()
- {
- _actions = new List<IAction>
- {
- new SleepAction(this),
- new EatAction(this),
- new DrinkAction(this),
- new HuntAction(this)
- };
- }
- private void Update()
- {
- IAction bestAction = GetBestAction();
- bestAction.Execute();
- }
- private IAction GetBestAction()
- {
- float bestUtility = float.MinValue;
- IAction bestAction = null;
- foreach(IAction action in _actions)
- {
- float utility = action.GetUtility();
- if (utility > bestUtility)
- {
- bestUtility = utility;
- bestAction = action;
- }
- }
- return bestAction;
- }
- private class SleepAction : IAction
- {
- private readonly AnimalAI _animal;
- public SleepAction(AnimalAI animal) =>
- _animal = animal;
- public void Execute()
- {
- Debug.Log("Sleeping");
- _animal._fatigue -= Time.deltaTime;
- _animal._hunger += Time.deltaTime * 0.5f;
- _animal._thirst += Time.deltaTime * 0.5f;
- }
- public float GetUtility()
- {
- return _animal._fatigue;
- }
- }
- private class EatAction : IAction
- {
- private readonly AnimalAI _animal;
- public EatAction(AnimalAI animal) =>
- _animal = animal;
- public void Execute()
- {
- _animal._hunger -= Time.deltaTime;
- _animal._fatigue += Time.deltaTime * 0.5f;
- _animal._thirst += Time.deltaTime * 0.5f;
- }
- public float GetUtility() => _animal._hunger;
- }
- private class DrinkAction : IAction
- {
- private readonly AnimalAI _animal;
- public DrinkAction(AnimalAI animal) =>
- _animal = animal;
- public void Execute()
- {
- _animal._thirst -= Time.deltaTime;
- _animal._fatigue += Time.deltaTime * 0.5f;
- _animal._hunger += Time.deltaTime * 0.5f;
- }
- public float GetUtility() => _animal._thirst;
- }
- private class HuntAction : IAction
- {
- private readonly AnimalAI _animal;
- public HuntAction(AnimalAI animal) =>
- _animal = animal;
- public void Execute()
- {
- _animal._fatigue += Time.deltaTime * 0.5f;
- _animal._hunger -= Time.deltaTime;
- _animal._thirst += Time.deltaTime * 0.5f;
- }
- public float GetUtility() =>
- _animal._hunger;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement