Unity 一个超级简单的有限状态机实现

0x01 直接上代码:

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
using UnityEngine;
using System.Collections;

public class Monster : MonoBehaviour {

public enum State {
Crawl,
Walk,
Die,
}

public State state;

IEnumerator CrawlState () {
Debug.Log("Crawl: Enter");
while (state == State.Crawl) {
yield return 0;
}
Debug.Log("Crawl: Exit");
NextState();
}

IEnumerator WalkState () {
Debug.Log("Walk: Enter");
while (state == State.Walk) {
yield return 0;
}
Debug.Log("Walk: Exit");
NextState();
}

IEnumerator DieState () {
Debug.Log("Die: Enter");
while (state == State.Die) {
yield return 0;
}
Debug.Log("Die: Exit");
}

void Start () {
NextState();
}

void NextState () {
string methodName = state.ToString() + "State";
System.Reflection.MethodInfo info =
GetType().GetMethod(methodName,
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Instance);
StartCoroutine((IEnumerator)info.Invoke(this, null));
}
}

0x02 代码解析:

  • 状态使用枚举表示
  • 直接给 state 变量赋值新的状态,系统将会迁移到下一个状态
  • NextState 根据当前 state 的值反射找出相应的状态函数且执行,比如当前状态为 Walk,将会调用 WalkState 方法
  • 每个 State 方法会经历Enter, While Loop Tick, Exit 三个过程。

0x03 其它有限状态机系统:

Unity3D - Simple Finite State Machine (C#)

thefuntastic/Unity3d-Finite-State-Machine

StateKit

prime31/StateKit