Metroidvania Devlog 5: State Machine Refactoring and Editor Tool
3/3/2023
In this post, I mentioned I was completely satisfied with the way the state machine system was working. And when you don't like something, you change it, if you can. And in programmer-land, you can always change your code. So I got to work changing the state machine system to something I find better and cleaner. I haven't yet implemented everything, but here's an outline:
StateMachineComponent
is attached to a game object and assigned aStateMachine
to work with- The
StateMachine
is started - Every frame, the
StateMachine
is ticked- The current
State
is ticked. This is where theState
acts and does something. - The current state has a list of
Transitions
associated with it, its exit transitions. - The
StateMachine
loops over every one of those transitions and calls itsDoTransition
method. This method returns abool
and aState
(through anout
parameter), wheretrue
means the transition should be done. All successfulTransitions
are collected, and then aTransition
is selected to be completed by means of a priority index. After aTransition
is selected, theStateMachine
changes to its returnedState
. If noTransition
is made theStateMachine
just remains in the sameState
.
- The current
- Every fixed frame, the
StateMachine
if fixed-ticked. This only fixed-ticks the current state, and doesn't process transitions.
Furthermore, every State
and Transition
has to its availability a set of data from different sources:
- each
StateMachine
asset has aScriptableObject
which holds global data. - there's also a lot of runtime data from different sources which can be read, such as the player's data, user input or game state.
In my opinion, these reworks make this system much better and cleaner.
The Editor
Of course, a StateMachine system needs a good graphical editor. And that's exactly what I made. Using the new UI Toolkit and the UI Builder, as well as experimental GraphView
component, I crafted an editor to create and connect states and set the conditions on a Transition
.
That's all I have to say for today. This was a shorter post, but making refactorings and an editor isn't much to write home about. I hope next time I can make something a bit longer. 'Til then, goodbye!