• Register

An indie game development group making games we would love to play.

RSS My Blogs

State Machines

clunkgames Blog

I've spent several days trying to figure out how to program a story. I already knew about the state machines, and used them several times (though, usually for parsers). But this time it has been again a little different.

GameController class is a top-level singleton manager of state machines. There are several state machines active during the gameplay. There are two types of state machines: root and side. The difference is that root machines are launched when the game starts, the side machines are launched later, on demand. Root machines are responsible for managing game charactes, items, doors, rooms, etc. Side machines are usually used for dialogs and animations.

State machines are not actually bound to any game object. They just exist separately "above". The primary reason is that I'm able to change states of any entity regardless of it's existence in the current scene.

The states have access to everything in the scene. They might be competing for the same game object, but that is handled simply by the designer himself. I use a simple rule, that a single state machine should only manage one entity in the game.

Each state has a piece of code to be executed when it's entered.

This a simple state machine for a door:


Door remain locked until a key no. 182 is picked up.

The locking/unlocking mechanism can be implemented several ways. Because door is a common object I would implement a default behavior on it's controller. So for example I would make three methods: Lock(), Unlock() and Enter(). In the "Locked" state I call door.Lock(), and in the "Unlocked" state I'd call door.Unlock(). Both will set internal boolean isLocked. When a player wants to enter the door, he will have to call Enter() method. The method will internally check if the door is locked and if not, it will request a scene to be changed. Other way would be to simply use a naming convention and in the Enter() method check if the current state if the door's state machine is called "Locked" or "Unlocked".

There might be a need for door target scene to depend on the key user has picked up. That way I would do this:


This time I would be also setting door's location in the state's code.

To design the state machines, I've made a small tool. The tool allows me to attach a plain-text to any node or connection. And it also saves the diagrams as easily readable JSON format. It's nothing fancy, but it does the job very well. I might have used PlayMaker or something like that, but I'm really not a big fan of no-programming-needed tools.

After that I've made a simple script that converts the JSON format into C# code, which is imported to Unity.

Post a comment

Your comment will be anonymous unless you join the community. Or sign in with your social account:

X