Finite State Machine
From Headbone Creative
Revision as of 16:40, 16 April 2013 by Tyson Joehler (Talk | contribs)
This page describes how to use this Finite State Machine Framework for Unity.
The three parts
There are three parts to this framework:
- A set of enums define the states in the state machine and the transitions between the states. These enums allow the programmer to easily define in plain terms how the states interact with each other and how one state transitions to another state.
- A State object that contains some basic functionality, but has some abstract functions that must be implemented in order to truly be useful. This is where you can implement different behaviors for the objects for each state.
- A System object that maintains a list of states and allows them to be accessed from a singular point. This class provides an interface to allow transitions to occur between states.
How to use the framework
- Create two files: one to hold the state objects that derive from FSMState, and one that derives from MonoBehavior, which will drive the state machine.
- In the file that will hold the state objects, create a namespace to hold the Transition and StateID enums, and the state objects you write.
- Add the Transition and StateID enums to the first file, using the following as a template:
- Write classes that derive from FSMState. This is where you can put behavior specific to the state that is being processed. Reason and Act will be called every frame that the state is active, in that order. See this page for more information:
- Create an instance of the FSMSystem class in the file that derives from MonoBehavior. Add a single instane of each state object to it. See this page for more information:
- Call ProcessCurrentState on the instance of FSMSystem from Update or FixedUpdate to drive the state machine.
/// <summary>
/// Place the labels for the Transitions in this enum.
/// Don't change the first label, NullTransition as FSMSystem class uses it.
/// </summary>
public enum Transition
{
NullTransition = 0, // Use this transition to represent a non-existing transition in your system
}
/// <summary>
/// Place the labels for the States in this enum.
/// Don't change the first label, NullTransition as FSMSystem class uses it.
/// </summary>
public enum StateID
{
NullStateID = 0, // Use this ID to represent a non-existing State in your system
}
Example
An example of how this framework can be used to implement AI can be found here:
A prefab using this script is included with the toolbox. It is demonstrated in the Sidescroller Demo