-
Notifications
You must be signed in to change notification settings - Fork 0
/
StateMachineManager.cs
86 lines (69 loc) · 2.49 KB
/
StateMachineManager.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class StateMachineManager : MonoBehaviour
{
[Header("Base StateMachine")]
[SerializeField] protected BaseState startingState;
[SerializeField] protected BaseState[] states;
[SerializeField] protected BaseState currentState;
[SerializeField] private float removeStateQueueTime;
private readonly List<BaseState> _switchStateQueue = new List<BaseState>();
protected void Awake()
{
SetStatesParent();
}
private void Start()
{
EnterStartingState();
}
protected void Update()
{
currentState.UpdateState(this);
}
protected void FixedUpdate()
{
currentState.FixedUpdateState(this);
if (!currentState.IsValidToSwitch || _switchStateQueue.Count <= 0) return;
SwitchState(_switchStateQueue[0]);
_switchStateQueue.Remove(_switchStateQueue[0]);
}
private void SetStatesParent()
{
foreach (var state in states)
{
state.SetParent(this);
}
}
private void EnterStartingState()
{
currentState = startingState;
currentState.EnterState(this);
}
/// <summary>
/// Switch the current targetState to a different one.
/// Is it valid to switch targetState?
/// </summary>
/// <param name="targetState">Give target state to switch into.</param>
/// <param name="isCalledFromExitState">If the SwitchState is called form a ExitState function, this needs to be true!</param>
public void SwitchState(BaseState targetState, bool isCalledFromExitState = false)
{
if (!currentState.IsValidToSwitch)
{
StartCoroutine(AddStateInQueue(targetState));
if(!_switchStateQueue.Contains(targetState)) return;
Debug.LogWarning("Switching targetState was not valid!!!\n" + currentState);
return;
}
if (!isCalledFromExitState) currentState.ExitState(this);
currentState = targetState;
targetState.EnterState(this);
}
private IEnumerator AddStateInQueue(BaseState queueableState)
{
_switchStateQueue.Add(queueableState);
Debug.Log("TargetState has been added to the state queue\n" + queueableState);
yield return new WaitForSeconds(removeStateQueueTime);
if (_switchStateQueue.Contains(queueableState)) _switchStateQueue.Remove(queueableState);
}
}