如果仅仅用一个枚举变量表示状态,那么状态切换的具体过程很难描述,所以需要设计一个有限状态机(FSM)来描述具体变换。针对每个状态,可以设计一个 State 类,该类首选包含一个当前状态的标识,然后是 Enter Update Exit 等状态切换时要做的 Action。有了这个结构,接下来做的便是绑定各个状态的方法,这里通过手动添加状态即可。最后设计好切换状态的方法即可,无非是先退出当前状态,再执行新状态的 Enter 方法。对于 Update 事件,可以在使用者 MonoBehaviour 的 Update 方法中调用即可。下面是一个简单的实现:

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

public class StateMachine<T> where T : struct, IComparable {

    private class State {
        public readonly T state;
        public readonly Action onEnter;
        public readonly Action onUpdate;
        public readonly Action onExit;

        public State(T state, Action onEnter, Action onUpdate, Action onExit) {
            this.state = state;
            this.onEnter = onEnter;
            this.onUpdate = onUpdate;
            this.onExit = onExit;
        }
    }

    private readonly Dictionary<T, State> stateDictionary;

    private State currentState;

    public T CurrentState {
        get { return currentState.state; }
        set { ChangeState (value); }
    }

    public StateMachine() {
        if (!typeof(T).IsEnum) {
            throw new ArgumentException ("类型参数必须为枚举");
        }
        stateDictionary = new Dictionary<T, State> ();
    }

    public void AddState (T state, Action onEnter, Action onUpdate, Action onExit) {
        stateDictionary.Add (state, new State (state, onEnter, onUpdate, onExit));
    }

    private void ChangeState(T newState) {
        if (currentState != null && currentState.state.CompareTo(newState) == 0) {
            return;
        }

        if (currentState != null && currentState.onExit != null) {
            currentState.onExit ();
        }

        currentState = stateDictionary [newState];

        if (currentState.onEnter != null) {
            currentState.onEnter ();
        }
    }

    public void Update() {
        if (currentState != null && currentState.onUpdate != null) {
            currentState.onUpdate ();
        }
    }
}

下面是测试代码

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

public class Test : MonoBehaviour {

    public enum CharacterState {
        Idle,
        Walk,
        Run,
    }

    private StateMachine<CharacterState> stateMachine;

    private WaitForSeconds waitSeconds;

    // Use this for initialization
    void Start () {
        stateMachine = new StateMachine<CharacterState> ();
        stateMachine.AddState (CharacterState.Idle, Idle_Enter, null, Idle_Exit);
        stateMachine.AddState (CharacterState.Walk, Walk_Enter, Walk_Update, Walk_Exit);
        stateMachine.AddState (CharacterState.Run, Run_Enter, null, Run_Exit);
        stateMachine.CurrentState = CharacterState.Idle;
        StartCoroutine (DoChange ());
    }

    IEnumerator DoChange () {
        waitSeconds = new WaitForSeconds (1f);
        yield return waitSeconds;
        stateMachine.CurrentState = CharacterState.Run;
        yield return waitSeconds;
        stateMachine.CurrentState = CharacterState.Walk;
        yield return waitSeconds;
        stateMachine.CurrentState = CharacterState.Idle;
    }
    
    // Update is called once per frame
    void Update () {
        stateMachine.Update ();
    }

    public void Idle_Enter () {
        Debug.Log ("Idle enter ...");
    }

    public void Idle_Exit () {
        Debug.Log ("Idle exit ***");
    }

    public void Walk_Enter () {
        Debug.Log ("Walk enter ...");
    }

    public void Walk_Update () {
        Debug.Log ("Walk update");
    }

    public void Walk_Exit () {
        Debug.Log ("Walk exit ***");
    }

    public void Run_Enter () {
        Debug.Log ("Run enter ...");
    }

    public void Run_Exit () {
        Debug.Log ("Run exit ***");
    }
}

另外一个状态机实现, https://github.com/thefuntastic/Unity3d-Finite-State-Machine.

StateMachineRunner.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
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;
using UnityEngine;
using Object = System.Object;

public class StateMachineRunner : MonoBehaviour
{
    private List<IStateMachine> stateMachineList = new List<IStateMachine>();

    /// <summary>
    /// Creates a stateMachine token object which is used to managed to the state of a monobehaviour. 
    /// </summary>
    /// <typeparam name="T">An Enum listing different state transitions</typeparam>
    /// <param name="component">The component whose state will be managed</param>
    /// <returns></returns>
    public StateMachine<T> Initialize<T>(MonoBehaviour component) where T : struct, IConvertible, IComparable
    {
        var fsm = new StateMachine<T>(this, component);

        stateMachineList.Add(fsm);

        return fsm;
    }

    /// <summary>
    /// Creates a stateMachine token object which is used to managed to the state of a monobehaviour. Will automatically transition the startState
    /// </summary>
    /// <typeparam name="T">An Enum listing different state transitions</typeparam>
    /// <param name="component">The component whose state will be managed</param>
    /// <param name="startState">The default start state</param>
    /// <returns></returns>
    public StateMachine<T> Initialize<T>(MonoBehaviour component, T startState) where T : struct, IConvertible, IComparable
    {
        var fsm = Initialize<T>(component);

        fsm.ChangeState(startState);

        return fsm;
    }

    void FixedUpdate()
    {
        for (int i = 0; i < stateMachineList.Count; i++)
        {
            var fsm = stateMachineList[i];
            if(!fsm.IsInTransition && fsm.Component.enabled) fsm.CurrentStateMap.FixedUpdate();
        }
    }

    void Update()
    {
        for (int i = 0; i < stateMachineList.Count; i++)
        {
            var fsm = stateMachineList[i];
            if (!fsm.IsInTransition && fsm.Component.enabled)
            {
                fsm.CurrentStateMap.Update();
            }
        }
    }

    void LateUpdate()
    {
        for (int i = 0; i < stateMachineList.Count; i++)
        {
            var fsm = stateMachineList[i];
            if (!fsm.IsInTransition && fsm.Component.enabled)
            {
                fsm.CurrentStateMap.LateUpdate();
            }
        }
    }

    //void OnCollisionEnter(Collision collision)
    //{
    //  if(currentState != null && !IsInTransition)
    //  {
    //      currentState.OnCollisionEnter(collision);
    //  }
    //}

    public static void DoNothing()
    {
    }

    public static void DoNothingCollider(Collider other)
    {
    }

    public static void DoNothingCollision(Collision other)
    {
    }

    public static IEnumerator DoNothingCoroutine()
    {
        yield break;
    }
}

public class StateMapping
{
    public object state;

    public bool hasEnterRoutine;
    public Action EnterCall = StateMachineRunner.DoNothing;
    public Func<IEnumerator> EnterRoutine = StateMachineRunner.DoNothingCoroutine;

    public bool hasExitRoutine;
    public Action ExitCall = StateMachineRunner.DoNothing;
    public Func<IEnumerator> ExitRoutine = StateMachineRunner.DoNothingCoroutine;

    public Action Finally = StateMachineRunner.DoNothing;
    public Action Update = StateMachineRunner.DoNothing;
    public Action LateUpdate = StateMachineRunner.DoNothing;
    public Action FixedUpdate = StateMachineRunner.DoNothing;
    public Action<Collision> OnCollisionEnter = StateMachineRunner.DoNothingCollision;

    public StateMapping(object state)
    {
        this.state = state;
    }
}

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
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;
using UnityEngine;
using Object = System.Object;

public enum StateTransition
{
    Safe,
    Overwrite,
}

public interface IStateMachine
{
    MonoBehaviour Component { get; }
    StateMapping CurrentStateMap { get; }
    bool IsInTransition { get; }
}

public class StateMachine<T> : IStateMachine where T : struct, IConvertible, IComparable
{
    public event Action<T> Changed;

    private StateMachineRunner engine;
    private MonoBehaviour component;

    private StateMapping lastState;
    private StateMapping currentState;
    private StateMapping destinationState;

    private Dictionary<object, StateMapping> stateLookup;

    private bool isInTransition = false;
    private IEnumerator currentTransition;
    private IEnumerator exitRoutine;
    private IEnumerator enterRoutine;
    private IEnumerator queuedChange;

    public StateMachine(StateMachineRunner engine, MonoBehaviour component)
    {
        this.engine = engine;
        this.component = component;

        //Define States
        var values = Enum.GetValues(typeof(T));
        if (values.Length < 1) { throw new ArgumentException("Enum provided to Initialize must have at least 1 visible definition"); }

        stateLookup = new Dictionary<object, StateMapping>();
        for (int i = 0; i < values.Length; i++)
        {
            var mapping = new StateMapping((Enum) values.GetValue(i));
            stateLookup.Add(mapping.state, mapping);
        }

        //Reflect methods
        var methods = component.GetType().GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public |
                                  BindingFlags.NonPublic);

        //Bind methods to states
        var separator = "_".ToCharArray();
        for (int i = 0; i < methods.Length; i++)
        {
            if (methods[i].GetCustomAttributes(typeof(CompilerGeneratedAttribute), true).Length != 0)
            {
                continue;
            }

            var names = methods[i].Name.Split(separator);

            //Ignore functions without an underscore
            if (names.Length <= 1)
            {
                continue;
            }

            Enum key;
            try
            {
                key = (Enum) Enum.Parse(typeof(T), names[0]);
            }
            catch (ArgumentException)
            {
                //Not an method as listed in the state enum
                continue;
            }

            var targetState = stateLookup[key];

            switch (names[1])
            {
                case "Enter":
                    if (methods[i].ReturnType == typeof(IEnumerator))
                    {
                        targetState.hasEnterRoutine = true;
                        targetState.EnterRoutine = CreateDelegate<Func<IEnumerator>>(methods[i], component);
                    }
                    else
                    {
                        targetState.hasEnterRoutine = false;
                        targetState.EnterCall = CreateDelegate<Action>(methods[i], component);
                    }
                    break;
                case "Exit":
                    if (methods[i].ReturnType == typeof(IEnumerator))
                    {
                        targetState.hasExitRoutine = true;
                        targetState.ExitRoutine = CreateDelegate<Func<IEnumerator>>(methods[i], component);
                    }
                    else
                    {
                        targetState.hasExitRoutine = false;
                        targetState.ExitCall = CreateDelegate<Action>(methods[i], component);
                    }
                    break;
                case "Finally":
                    targetState.Finally = CreateDelegate<Action>(methods[i], component);
                    break;
                case "Update":
                    targetState.Update = CreateDelegate<Action>(methods[i], component);
                    break;
                case "LateUpdate":
                    targetState.LateUpdate = CreateDelegate<Action>(methods[i], component);
                    break;
                case "FixedUpdate":
                    targetState.FixedUpdate = CreateDelegate<Action>(methods[i], component);
                    break;
                case "OnCollisionEnter":
                    targetState.OnCollisionEnter = CreateDelegate<Action<Collision>>(methods[i], component);
                    break;
            }
        }

        //Create nil state mapping
        currentState = new StateMapping(null);
    }

    private V CreateDelegate<V>(MethodInfo method, Object target) where V : class
    {
        var ret = (Delegate.CreateDelegate(typeof(V), target, method) as V);

        if (ret == null)
        {
            throw new ArgumentException("Unabled to create delegate for method called " + method.Name);
        }
        return ret;
    }

    public void ChangeState(T newState)
    {
        ChangeState(newState, StateTransition.Safe);
    }

    public void ChangeState(T newState, StateTransition transition)
    {
        if (stateLookup == null)
        {
            throw new Exception("States have not been configured, please call initialized before trying to set state");
        }

        if (!stateLookup.ContainsKey(newState))
        {
            throw new Exception("No state with the name " + newState.ToString() + " can be found. Please make sure you are called the correct type the statemachine was initialized with");
        }

        var nextState = stateLookup[newState];

        if (currentState == nextState) return;

        //Cancel any queued changes.
        if (queuedChange != null)
        {
            engine.StopCoroutine(queuedChange);
            queuedChange = null;
        }

        switch (transition)
        {
            //case StateMachineTransition.Blend:
            //Do nothing - allows the state transitions to overlap each other. This is a dumb idea, as previous state might trigger new changes. 
            //A better way would be to start the two couroutines at the same time. IE don't wait for exit before starting start.
            //How does this work in terms of overwrite?
            //Is there a way to make this safe, I don't think so? 
            //break;
            case StateTransition.Safe:
                if (isInTransition)
                {
                    if (exitRoutine != null) //We are already exiting current state on our way to our previous target state
                    {
                        //Overwrite with our new target
                        destinationState = nextState;
                        return;
                    }

                    if (enterRoutine != null) //We are already entering our previous target state. Need to wait for that to finish and call the exit routine.
                    {
                        //Damn, I need to test this hard
                        queuedChange = WaitForPreviousTransition(nextState);
                        engine.StartCoroutine(queuedChange);
                        return;
                    }
                }
                break;
            case StateTransition.Overwrite:
                if (currentTransition != null)
                {
                    engine.StopCoroutine(currentTransition);
                }
                if (exitRoutine != null)
                {
                    engine.StopCoroutine(exitRoutine);
                }
                if (enterRoutine != null)
                {
                    engine.StopCoroutine(enterRoutine);
                }

                //Note: if we are currently in an EnterRoutine and Exit is also a routine, this will be skipped in ChangeToNewStateRoutine()
                break;
        }


        if ((currentState != null && currentState.hasExitRoutine) || nextState.hasEnterRoutine)
        {
            isInTransition = true;
            currentTransition = ChangeToNewStateRoutine(nextState, transition);
            engine.StartCoroutine(currentTransition);
        }
        else //Same frame transition, no coroutines are present
        {
            if (currentState != null)
            {
                currentState.ExitCall();
                currentState.Finally();
            }

            lastState = currentState;
            currentState = nextState;
            if (currentState != null)
            {
                currentState.EnterCall();
                if (Changed != null)
                {
                    Changed((T) currentState.state);
                }
            }
            isInTransition = false;
        }
    }

    private IEnumerator ChangeToNewStateRoutine(StateMapping newState, StateTransition transition)
    {
        destinationState = newState; //Chache this so that we can overwrite it and hijack a transition

        if (currentState != null)
        {
            if (currentState.hasExitRoutine)
            {
                exitRoutine = currentState.ExitRoutine();

                if (exitRoutine != null && transition != StateTransition.Overwrite) //Don't wait for exit if we are overwriting
                {
                    yield return engine.StartCoroutine(exitRoutine);
                }

                exitRoutine = null;
            }
            else
            {
                currentState.ExitCall();
            }

            currentState.Finally();
        }

        lastState = currentState;
        currentState = destinationState;

        if (currentState != null)
        {
            if (currentState.hasEnterRoutine)
            {
                enterRoutine = currentState.EnterRoutine();

                if (enterRoutine != null)
                {
                    yield return engine.StartCoroutine(enterRoutine);
                }

                enterRoutine = null;
            }
            else
            {
                currentState.EnterCall();
            }

            //Broadcast change only after enter transition has begun. 
            if (Changed != null)
            {
                Changed((T) currentState.state);
            }
        }

        isInTransition = false;
    }

    IEnumerator WaitForPreviousTransition(StateMapping nextState)
    {
        while (isInTransition)
        {
            yield return null;
        }

        ChangeState((T) nextState.state);
    }

    public T LastState
    {
        get
        {
            if (lastState == null) return default(T);

            return (T) lastState.state;
        }
    }

    public T State
    {
        get { return (T) currentState.state; }
    }

    public bool IsInTransition
    {
        get { return isInTransition; }
    }

    public StateMapping CurrentStateMap
    {
        get { return currentState; }
    }

    public MonoBehaviour Component
    {
        get { return component; }
    }

    /// <summary>
    /// Inspects a MonoBehaviour for state methods as definied by the supplied Enum, and returns a stateMachine instance used to trasition states.
    /// </summary>
    /// <param name="component">The component with defined state methods</param>
    /// <returns>A valid stateMachine instance to manage MonoBehaviour state transitions</returns>
    public static StateMachine<T> Initialize(MonoBehaviour component)
    {
        var engine = component.GetComponent<StateMachineRunner>();
        if (engine == null) engine = component.gameObject.AddComponent<StateMachineRunner>();

        return engine.Initialize<T>(component);
    }

    /// <summary>
    /// Inspects a MonoBehaviour for state methods as definied by the supplied Enum, and returns a stateMachine instance used to trasition states. 
    /// </summary>
    /// <param name="component">The component with defined state methods</param>
    /// <param name="startState">The default starting state</param>
    /// <returns>A valid stateMachine instance to manage MonoBehaviour state transitions</returns>
    public static StateMachine<T> Initialize(MonoBehaviour component, T startState)
    {
        var engine = component.GetComponent<StateMachineRunner>();
        if (engine == null) engine = component.gameObject.AddComponent<StateMachineRunner>();

        return engine.Initialize<T>(component, startState);
    }

}

下面是一个使用范例 Main.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
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
using UnityEngine;
using System.Collections;

public class Main : MonoBehaviour
{
    //Declare which states we'd like use
    public enum States
    {
        Init,
        Countdown,
        Play,
        Win,
        Lose
    }

    public float health = 100;
    public float damage = 20;

    private float startHealth;

    private StateMachine<States> fsm;

    private void Awake()
    {
        startHealth = health;

        //Initialize State Machine Engine       
        fsm = StateMachine<States>.Initialize(this, States.Init);
    }

    void OnGUI()
    {
        //Example of polling state 
        var state = fsm.State;

        GUILayout.BeginArea(new Rect(50,50,120,40));

        if(state == States.Init && GUILayout.Button("Start"))
        {
            fsm.ChangeState(States.Countdown);
        }
        if(state == States.Countdown)
        {
            GUILayout.Label("Look at Console");
        }
        if(state == States.Play)
        {
            if(GUILayout.Button("Force Win"))
            {
                fsm.ChangeState(States.Win);
            }
            
            GUILayout.Label("Health: " + Mathf.Round(health).ToString());
        }
        if(state == States.Win || state == States.Lose)
        {
            if(GUILayout.Button("Play Again"))
            {
                fsm.ChangeState(States.Countdown);
            }
        }

        GUILayout.EndArea();
    }

    private void Init_Enter()
    {
        Debug.Log("Waiting for start button to be pressed");
    }

    //We can return a coroutine, this is useful animations and the like
    private IEnumerator Countdown_Enter()
    {
        health = startHealth;

        Debug.Log("Starting in 3...");
        yield return new WaitForSeconds(0.5f);
        Debug.Log("Starting in 2...");
        yield return new WaitForSeconds(0.5f);
        Debug.Log("Starting in 1...");
        yield return new WaitForSeconds(0.5f);

        fsm.ChangeState(States.Play);
    }

    private void Play_Enter()
    {
        Debug.Log("FIGHT!");
    }

    private void Play_Update()
    {
        health -= damage * Time.deltaTime;
    
        if(health < 0)
        {
            fsm.ChangeState(States.Lose);
        }
    }

    void Play_Exit()
    {
        Debug.Log("Game Over");
    }

    void Lose_Enter()
    {
        Debug.Log("Lost");
    }

    void Win_Enter()
    {
        Debug.Log("Won");
    }
}