Survivalcraft API 1.8.2.3 v1.8.2.3
Survivalcraft 2.4
载入中...
搜索中...
未找到
StateMachine.cs
浏览该文件的文档.
1namespace Game {
2 public class StateMachine {
3 public class State {
4 public string Name;
5
6 public Action Enter;
7
8 public Action Update;
9
10 public Action Leave;
11 }
12
13 public Dictionary<string, State> m_states = [];
14
16
18
19 public string PreviousState {
20 get {
21 if (m_previousState == null) {
22 return null;
23 }
24 return m_previousState.Name;
25 }
26 }
27
28 public string CurrentState {
29 get {
30 if (m_currentState == null) {
31 return null;
32 }
33 return m_currentState.Name;
34 }
35 }
36
37 public event Action<string> OnTransitionTo;
38
39 public void AddState(string name, Action enter, Action update, Action leave) {
40 if (string.IsNullOrEmpty(name)) {
41 throw new Exception("State name must not be empty or null.");
42 }
43 m_states.Add(name, new State { Name = name, Enter = enter, Update = update, Leave = leave });
44 }
45
46 public void TransitionTo(string stateName) {
47 State state = FindState(stateName);
48 if (state != m_currentState) {
49 if (m_currentState != null
50 && m_currentState.Leave != null) {
51 m_currentState.Leave();
52 }
54 m_currentState = state;
55 if (m_currentState != null
56 && m_currentState.Enter != null) {
57 m_currentState.Enter();
58 }
59 OnTransitionTo?.Invoke(stateName);
60 }
61 }
62
63 public virtual void Update() {
64 if (m_currentState != null
65 && m_currentState.Update != null) {
66 m_currentState.Update();
67 }
68 }
69
70 public State FindState(string name) {
71 if (!string.IsNullOrEmpty(name)) {
72 if (!m_states.TryGetValue(name, out State value)) {
73 throw new InvalidOperationException($"State \"{name}\" not found.");
74 }
75 return value;
76 }
77 return null;
78 }
79 }
80}
Action< string > OnTransitionTo
virtual void Update()
void TransitionTo(string stateName)
void AddState(string name, Action enter, Action update, Action leave)
Dictionary< string, State > m_states
State FindState(string name)