StateMachine Best Practices ( Mecanim ? )

Hello Folks,

I am currently reading a book about Unity AI Game Programming. I am currently building a turn based rpg game. Therfore I created 3 Statemachines. One for the Encounter, one for the Player and one for AI Enemies.

All 3 Statemachines are build in the same way :

  • Each statemachine is a class
  • States as enums, declared within the class
  • Switch statement in the update method

Now I found out in the book, they create a statemachine using mecanim. Now i am not sure what’s the best way to create a statemachine in unity.

Mecanim has some advantages. Above all, the improved visual representation of the machine and the individual states and their transitions.

So I tried to replace my statemachine with a mecanim statemachine. But I’m not sure how I would handle animations and a statemachine on the same prefab now, because you only can have one Animation Controller on a prefab.

So my questions are :

  • Is Mecanim the current standard how to create finite state machines ? Or is there a better way ?
  • How would you handle animations and a FSM on the same prefab?

Greetings

I personally would make it using mecanim + statemachinebehaviour. You can visually debug it, it links very nicely with other mecanim systems such as animation (and therefore can make animating much easier).

You can link the statemachinebehaviour in a slot in the inspector on your animation state machine to get a behaviour to play on entering exiting etc a state.

https://docs.unity3d.com/ScriptReference/StateMachineBehaviour.html

https://unity3d.com/learn/tutorials/modules/beginner/5-pre-order-beta/state-machine-behaviours

Is there a way to create a kind of abstract state machine with Mecanim ? Currently the player and the enemies state machines derive from the same state machine so the EncounterFSM can interact with both statemachines.

That is what i currently build and want to recreate with mecanim :

  • The EncounterFSM controlls who is on the move. So it sets the PlayerFSM or EnemyFSM to the state DOACTION.
  • While the PlayerFSM or EnemyFSM is in DOACTION, the player for example can run around, cast speels etc.
  • After the Player or the AI finished his turn, the EncounterFSM is set to the state NEXT, so it will active the next Player/Enemy in line.

While the PlayerFSM is in the DOACTION state, it should player different Animations, depending on the action the Player is doing, for example, running animation, spell cast animation, attack animation etc.

Any hints on how to achieve this with mecanim ?