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
{
    [CreateAssetMenu(menuName = "Finite State Machine/FSM")]
    public class FSM : ScriptableObject
    {
        private NPCConroller controller;
        [SerializeField] private State initialState;
        [SerializeField] private State currentState;
        [SerializeField] private GameObject target;
        public NPCConroller Controller => controller;

        public void SetUp(NPCConroller conroller)
        {
            SetContoller(conroller);

            if (initialState != null)
            {
                Debug.Log($"{controller.gameObject.name} initial state is {initialState}");
                initialState.GetentryActions();
                currentState = initialState;
            }

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

        // Called Every Frame
        public void GUpdate()
        {
            Debug.Log("FSM UPDATING");
            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
            state.EnterState(this);
        }

        public State CurrentState() => currentState;

        private void SetContoller(NPCConroller controller) => this.controller = controller;
    }
}