Using a C# Abstract Class to construct a Finite State Machines (FSM)

I had downloaded the free M2H C# examples from the Unity Store so I could learn C# while learning to use the 3D Unity and Monodevelop software.

A GameObject in the Scene has a script attached to it in order for the GameObject to do something. M2H used a simple finite state machine to control the GameObject. It was very clever.

In the M2H examples, the programmer was using a simple finite state machine to switch (transistion) from one state to another. Because there were not that many states to control, he simply used a switch statement.

For more complex Non-player-characters with 5 or mores states, is it feasible to use C# abstract Class instead of a switch statement? If so, did you use the abstract methods Enter(), Update(), Exit(), Init(), CheckTransitions(), etc. for the State Class?

Thanks CSDG.

Absolutely. A abstract class in C# just provides inheritance, and in your case, I think an interface would work just as well. Just remember that you should only put common functionality into your inherited structures, not implementation specific code.


I have completed incorporating the FSM from UnifyCommunity but sad to say it did not work. There was some redundancies in the coding. He used both a transition and a stateID in the enumerations. If you delete the transition enumeration and then tidy up the rest of the code, it works great.

Thanks CSDG

In practice, any given state is going to have only a few transitions, and there will be a lot of odd exceptions. Spaghetti code seems about the best way. What I mean is, the behavior we want might be all over the map:

// massive damage:
AIstate=flee; AItimeLeft = damageTaken*0.1;

// morale failure:
AIstate=flee; AItimeLeft = Random.value*2+3;

// use morale spell:
foreach friendly
if(AIstate==flee) { AItimeLeft-=spellPower; if(AItime<0) AIstate=ready; }

// standard AI check:
  if(AItimeLeft<0) {
    if(health<25%) AIstate=travelling; target=nearestRepairBase; }
    else { AIstate=ready; }

if(target!=null & near target) {
  if(AIstate==flee) pick new target away from baddies