This repository has been archived by the owner on Apr 4, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
StateMachine.cs
73 lines (61 loc) · 1.79 KB
/
StateMachine.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
using System;
using System.Collections.Generic;
using UnityEngine;
namespace CoinFlipGames.FSM
{
public class StateMachine : MonoBehaviour
{
private class State
{
public Enum Name { get; private set; }
public Action<Enum> OnEnter { get; private set; }
public Action OnUpdate { get; private set; }
public Action<Enum> OnExit { get; private set; }
public State (Enum name, Action<Enum> enterCallback, Action updateCallback, Action<Enum> exitCallback)
{
this.Name = name;
this.OnEnter = enterCallback;
this.OnUpdate = updateCallback;
this.OnExit = exitCallback;
}
}
private Dictionary<Enum, State> states;
private State currentState;
private State previousState;
public Enum CurrentState { get { return currentState.Name; } }
public Enum PreviousState { get { return previousState.Name; } }
public void AddState (Enum name, Action<Enum> enterCallback, Action updateCallback, Action<Enum> exitCallback)
{
State state = new State (name, enterCallback, updateCallback, exitCallback);
this.states.Add (state.Name, state);
if (null == this.currentState) {
this.currentState = state;
state.OnEnter (null);
}
}
public void Switch (Enum to)
{
if (!this.states.ContainsKey (to)) {
Debug.LogError ("No state by the name '" + to + "'.");
return;
}
// Switch current to previous and pull new state by name
this.previousState = this.currentState;
this.currentState = this.states [to];
// Leave previous state
this.previousState.OnExit (this.CurrentState);
// Enter new state
this.currentState.OnEnter (this.PreviousState);
}
void Awake ()
{
this.states = new Dictionary<Enum, State> ();
}
void Update ()
{
if (null != this.currentState) {
this.currentState.OnUpdate ();
}
}
}
}