- Home /
How to implement a basic Stacked based Finiste state machine design?
Hi!, In the past week i have learnt and implemented a simple game using unity, where i have a character who has to do a set of obstacles to complete a level and as of now my character is able to jump and hit.
I was going through some design patterns and have found a method called 'Stack based Finite State Machine' which would allow me to stack my events like jump,hit,kick(more to be added) into stacks where i would call my respective functions so it would be easier for me to add new features and i will have a clean code throughout.
I have looked through unity answers/forums and havent been able to find out of how i should design/implement it. If anyone could help me out with this/show me where i can look for like a tutorial on how to implement it, it would be great!
Thanks in advance!
Answer by jammingames · Aug 26, 2014 at 04:23 AM
This is an old question, but if you're looking for an extremely simple stack based FSM this may help you note the second class can be in it's own script, it just extends List to include basic Push(); and Pop(); methods
using System.Collections.Generic;
using System.Collections;
using System;
public class FSM
{
List<System.Action> states;
public FSM ()
{
this.states = new List<System.Action> ();
}
public void DoState ()
{
var currentStateFunction = GetCurrentState ();
if (currentStateFunction != null)
currentStateFunction ();
}
public System.Action PopState ()
{
return states.Pop ();
}
public void PushState (System.Action state)
{
if (GetCurrentState () != state)
states.Push (state);
}
public System.Action GetCurrentState ()
{
return states.Count > 0 ? states [states.Count - 1] : null;
}
}
public static class ListExtensions
{
public static T Pop<T> (this List<T> theList)
{
var local = theList [theList.Count - 1];
theList.RemoveAt (theList.Count - 1);
return local;
}
public static void Push<T> (this List<T> theList, T item)
{
theList.Add (item);
}
}
Answer by HeywoodFloyd · Dec 01, 2010 at 05:57 PM
Mono has two stack classes (that I know of). I use C#, and would use System.Collections.Generic.Stack, because generics are cool.
Make a base class for the actions you want to push on the stack, and have all your actions specialize it. If you don't want to specialize MonoBehaviour, you can make them an internal classes of whatever MonoBehaviour is managing your stack, or you can put it in the Standard Assets folder, ensuring it's compiled before your other scripts. (I like the internal classes solution so I don't have to remember where I put files, but it leads to really big files.)
Thanks for your reply, but i'm still very confused on how to actually implement it.As of now my player does 2 things, he kicks and jumps.Could you maybe give me an example of ow to create a stack fsm wherein i can use both these events as states and push and pop them whenever necessary.