Hey ya’ll. While making my game I realized that managing state isn’t entirely too easy. I have seen many many solutions from other developers that are generally over-engineered (mostly from first year CS students), so I decided to create my own module for this.
You can find the source code here: GitHub - tannnxr/StateMachine: This is a simple state machine for Roblox.
Feel free to contribute to it.
Tutorial
Go to the Github Repo and copy the raw script.
Create a new script in wherever you want the module to be accessed from.
Then require the module and instantiate a new StateMachine like so.
local StateMachine = require(--[[ Path to Module ]])
-- [[ The state machine will always set the first state as the default state ]]
local playerState = StateMachine.newState({"Running", "Walking", "Jumping", "Falling"})
Congratulations! You just created a state machine.
But how do we actually manage state?? Glad you asked. Let me show you how to set states.
-- Obviously create your state machine first
playerState:setState("Jumping")
Congratualtions, the state has now been changed from the first state (default) “Running” to “Jumping”
Keep in mind you can only change the state to a state that you instantiated the StateMachine.
But tanner, how do we get the state from the machine, so far you only showed us how to create it and how to set a state!!!
Glad you asked, because I made this method last minute completely forgetting that you’d need to be able to get the state.
playerState:getCurrentState()
This will return the current state from the machine.
But what if I want to get the state anytime it changes so I can modify things in real time. Don’t worry, I got you. There are BindableEvents
for you!
Simply do this:
playerState.stateChanged.Event:Connect(function(oldState, newState)
print(`State Changed: {oldState} -> {newState}`)
end)
What about error handling?? Well I wanted to leave that up to you (the developer) to decide how to handle errors so I just added in another bindable event for errors.
playerState.error.Event:Connect(function(msg)
print(msg)
end)
This is fairly versatile, so feel free to do what you want with it!!!
Also please do contribute to make this module better, I genuinely need help im going insane.
Edits
#1 If there are any issues or bugs with the code please do open an issue for myself or another contributer to fix.