Newer
Older
TheVengeance-Project-IADE-Unity2D / Assets / Scripts / NPC / FSM / FSM.cs
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. namespace MyCollections.AI.FinitStateMachine
  6. {
  7. public class FSM : MonoBehaviour
  8. {
  9. private NPCController controller;
  10. [SerializeField] private State initialState;
  11. [SerializeField] private State currentState;
  12. public NPCController Controller => controller;
  13. private void Awake()
  14. {
  15. controller = GetComponent<NPCController>();
  16. }
  17. private void Start()
  18. {
  19. if (initialState != null)
  20. {
  21. initialState.EnterState(this);
  22. currentState = initialState;
  23. }
  24. else
  25. {
  26. Debug.LogError($"The NPC doesn't have an Initial State");
  27. }
  28. }
  29. // Called Every Frame
  30. public void Update()
  31. {
  32. if (currentState != null)
  33. {
  34. if (currentState.GetActions().Count > 0)
  35. {
  36. foreach (Action action in currentState.GetActions())
  37. {
  38. action.Run(this);
  39. }
  40. }
  41. Transition triggeredTransition = currentState.GetTriggeredTransition(this);
  42. if (triggeredTransition != null)
  43. {
  44. ChangeState(triggeredTransition.TargetState());
  45. }
  46. }
  47. }
  48. public void ChangeState(State state)
  49. {
  50. currentState.GetExitAction()?.Run(this); //Runs the exit action
  51. currentState = state;
  52. state.EnterState(this);
  53. }
  54. public State CurrentState() => currentState;
  55. public void SetInitialState(State initialState)
  56. {
  57. this.initialState = initialState;
  58. currentState = initialState;
  59. currentState.EnterState(this);
  60. }
  61. }
  62. }