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:
StateMachineComponentis attached to a game object and assigned aStateMachineto work with- The
StateMachineis started - Every frame, the
StateMachineis ticked- The current
Stateis ticked. This is where theStateacts and does something. - The current state has a list of
Transitionsassociated with it, its exit transitions. - The
StateMachineloops over every one of those transitions and calls itsDoTransitionmethod. This method returns abooland aState(through anoutparameter), wheretruemeans the transition should be done. All successfulTransitionsare collected, and then aTransitionis selected to be completed by means of a priority index. After aTransitionis selected, theStateMachinechanges to its returnedState. If noTransitionis made theStateMachinejust remains in the sameState.
- The current
- Every fixed frame, the
StateMachineif 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
StateMachineasset has aScriptableObjectwhich 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!