Newer
Older
TheVengeance-Project-IADE-Unity2D / Assets / Scripts / NPC / FSM / FSM.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace MyCollections.AI.FinitStateMachine
{
    public class FSM : MonoBehaviour
    {
        private NPCController controller;
        [SerializeField] private State initialState;
        [SerializeField] private State currentState;
        public NPCController Controller => controller;

        private void Awake()
        {
            controller = GetComponent<NPCController>();
        }

        private void Start()
        {
            if (initialState != null)
            {
                initialState.EnterState(this);
                currentState = initialState;
            }

            else
            {
                Debug.LogError($"The NPC doesn't have an Initial State");
            }
        }

        // Called Every Frame
        public void Update()
        {
            if (currentState != null)
            {
                if (currentState.GetActions().Count > 0)
                {
                    foreach (Action action in currentState.GetActions())
                    {
                        action.Run(this);
                    }
                }

                Transition triggeredTransition = currentState.GetTriggeredTransition(this);

                if (triggeredTransition != null)
                {
                    ChangeState(triggeredTransition.TargetState());
                }
            }
        }

        public void ChangeState(State state)
        {
            currentState.GetExitAction()?.Run(this); //Runs the exit action
            currentState = state;
            state.EnterState(this);
        }

        public State CurrentState() => currentState;
        public void SetInitialState(State initialState)
        {
            this.initialState = initialState;
            currentState = initialState;
            currentState.EnterState(this);
        }
    }
}