Finite State Machine

From Headbone Creative
Revision as of 21:35, 16 April 2013 by Tyson Joehler (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

This page describes how to use this Finite State Machine Framework for Unity. It is based on this code from the Unify Community wiki: Finite State Machine

The three parts

There are three parts to this framework:

  1. 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.
  2. 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.
  3. 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

  1. 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.
  2. 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.
  3. Add the Transition and StateID enums to the first file, using the following as a template:
  4. 
       /// <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   
       }
    

  5. 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.
  6. Create an instance of the FSMSystem class in the file that derives from MonoBehavior. Add a single instane of each state object to it.
  7. Call ProcessCurrentState on the instance of FSMSystem from Update or FixedUpdate to drive the state machine.

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

Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox