Finite State Machine

Description
This is a Deterministic Finite State Machine framework based on chapter 3.1 of Game Programming Gems 1 by Eric Dybsend. Therea are two classes and two enums. Include them in your project and follow the explanations to get the FSM working properly. There's also a complete example script at the end of this page.

Components

 * Transition enum: This enum contains the labels to the transitions that can be fired by the system. Don't change the first label, NullTransition, as the FSMSystem class uses it.


 * StateID enum: This is the ID of the states the game may have. You could use references to the real States' classes but using enums makes the system less susceptible to have code having access to objects it is not supposed to. All the states' ids should be placed here. Don't change the first label, NullStateID, as the FSMSystem class uses it.


 * FSMState class: This class has a Dictionary with pairs (Transition-StateID) indicating which new state S2 the FSM should go to when a transition T is fired and the current state is S1. It has methods to add and delete pairs (Transition-StateID), a method to check which state to go to if a transition is passed to it. Two methods are used in the example given to check which transition should be fired (Reason) and which action(s) (Act) the GameObject that has the FSMState attached should do. You don't have to use this schema, but some kind of transition-action code must be used in your game.


 * FSMSystem: This is the Finite State Machine class that each NPC or GameObject in your game must have in order to use the framework. It stores the NPC's States in a List, has methods to add and delete a state and a method to change the current state based on a transition passed to it (PerformTransition). You can call this method anywhere within your code, as in a collision test, or within Update or FixedUpdate.

Example
Here's an example that implements the above framework. The GameObject with this script follows a path of waypoints and starts chasing a target if it comes within a certain distance from it. Attach this class to your NPC. Besides the framework transition and stateid enums, you also have to setup a reference to the waypoints and to the target (player). I used FixedUpdate in the MonoBehaviour because the NPC reasoning schema doesn't need to be called every frame, but you can change that and use Update.