Skip to content

Instantly share code, notes, and snippets.

@dinodeck
Last active March 14, 2019 20:29
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dinodeck/b976cc95ab4c37a94ada to your computer and use it in GitHub Desktop.
Save dinodeck/b976cc95ab4c37a94ada to your computer and use it in GitHub Desktop.
A simple reusable statemachine written in C#.
using System;
using System.Collections;
using System.Collections.Generic;
public interface IState
{
void Update(float dt);
void HandleInput();
void Enter(params object[] args);
void Exit();
}
public class EmptyState : IState
{
public void Update(float dt) {}
public void HandleInput() {}
public void Enter(params object[] args) {}
public void Exit() {}
}
public class StateMachine
{
Dictionary<string, IState> _stateDict = new Dictionary<string, IState>();
IState _current = new EmptyState();
public IState Current { get { return _current; } }
public void Add(string id, IState state) { _stateDict.Add(id, state); }
public void Remove(string id) { _stateDict.Remove(id); }
public void Clear() { _stateDict.Clear(); }
public void Change(string id, params object[] args)
{
_current.Exit();
IState next = _stateDict[id];
next.Enter(args);
_current = next;
}
public void Update(float dt)
{
_current.Update (dt);
}
public void HandleInput()
{
_current.HandleInput();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment