Before i start i would advise you to watch this video to help with your understanding of state machines and how to apply this knowledge to roblox studio:
Why should you be using state machines?
If you’re anything like me and often get tangled in a jumble of words I somehow call code, you’ve probably faced the issue of forgetting how a scripts link together or how one variable connects to another. That’s where state machines come in handy!
State machines are an excellent tool to make your game logic more organized, predictable, and easier to maintain. In this post, I’ll explain what state machines are while also applying it to Roblox Studio, why you should be using them, and how they can make your development process smoother.
What is a State Machine?
In Roblox Studio, a state machine is a system that controls the different states an object or character can be in and how it transitions between those states. A “state” is simply a condition or mode, like “Idle,” “Running,” or “Jumping” for a character.
How Do State Machines Work in Roblox?
First off, i strongly recommend creating a sketch of what the core states your character/npc your character is trying to achieve are. An example below >
Then you either have to create the states ( i say either because some core states like idle/run are built into roblox) like attacking or figure out how to transition between state to state.
Here’s an example of how I’ve used state machines in my script. From my initial plan, I knew I only wanted the character to attack when it was in either the walk or idle state. So, between lines 47 and 54, I check if the character is in any states where attacking shouldn’t be allowed. Then, on lines 60 to 62, I stop the script (prevent the attack) if it’s in one of those unwanted states. I could have simply checked if the character was in the idle or walk state, but that didn’t occur to me at the time. …
Use case inspiration:
In case you weren’t aware, state machines are a technique that extends well beyond Roblox Studio. Many triple-A games use this method. For example, in boss battles like those in Elden Ring, state machines help the bosses determine when to attack based on the player’s distance or their current phase. Stealth games like Metal Gear or Assassin’s Creed also use this to control enemy AI, allowing them to react logically, like taking cover or firing when they spot a player. In short, state machines are a valuable tool that can save you time by preventing the need to constantly re-read or rewrite confusing code. It’s worth trying out, as the concept is easy to learn and quick to implement.
If you have any more to add to this, please feel free to leave a comment on my video or on the post to help out.