Last active
March 14, 2019 20:29
-
-
Save dinodeck/b976cc95ab4c37a94ada to your computer and use it in GitHub Desktop.
A simple reusable statemachine written in C#.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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