Skip to content

Instantly share code, notes, and snippets.

@goshdarngames
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save goshdarngames/a150b34995de00726206 to your computer and use it in GitHub Desktop.
Save goshdarngames/a150b34995de00726206 to your computer and use it in GitHub Desktop.
Finite State Machine in CSharp
/*****************************************************************************
* State.cs
*
* This interface allows an object to be treated as a State by a State
* Machine.
****************************************************************************/
using UnityEngine;
using System.Collections;
namespace FiniteStateMachine
{
public interface State
{
/// <summary>
/// Called when the state is made active by the state machine.
/// </summary>
void setup();
/// <summary>
/// Called each time Update is called by the Unity engine.
/// </summary>
void update();
/// <summary>
/// Called when the state machine changes state to allow the
/// state to clean up.
/// </summary>
void teardown();
}
}
/*****************************************************************************
* StateMachine.cs
*
* A finite state machine that allows an object to have multiple states
* and handle updates in a consistent way.
****************************************************************************/
using UnityEngine;
using System.Collections;
namespace FiniteStateMachine
{
public class StateMachine
{
/*********************************************************************
* PRIVATE DATA
********************************************************************/
private State currentState;
/*********************************************************************
* CONSTRUCTOR
********************************************************************/
public StateMachine(State initialState)
{
this.changeState (initialState);
}
/*********************************************************************
* PUBLIC METHODS
********************************************************************/
/// <summary>
/// Changes the state. Calls teardown on current state (if it exists)
/// and calls setup on the new state.
/// </summary>
/// <param name="newState">New state to switch to.</param>
public void changeState(State newState)
{
if(this.currentState != null)
{
this.currentState.teardown();
}
newState.setup ();
this.currentState = newState;
}
/// <summary>
/// Update the current state.
///
/// A null pointer exception will occur if the state is null.
/// </summary>
public void update()
{
this.currentState.update ();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment