Unity & Playmaker - Building a Keypad

Update: There's an updated version of this post, complete with source code and the full project here: http://www.stephen-gurnett.org/unlikely-objects/2014/11/20/unity-playmaker-building-a-keypad

I've been experimenting with Unity for making games and prototypes more quickly. One of the things I picked up in the recent Unity sale was Playmaker. When I first started out programming I wanted to do everything myself. I'm in two minds about the benefits of this. On the one hand, I learnt a lot of things (mostly what not to do but that is kind of useful as well). On the other, now I know those things I also know I don't have the time to spend on them. 

I want to put together a quick project to provide as a little birthday gift to someone. It's little more than an animated card but I wanted to put some interactivity in there just to provide a little entertainment. It's also a good excuse to learn putting how to work with Unity (and Blender as well).

The view in game (debugging shows the state of the FSM on the Game Object).

The view in game (debugging shows the state of the FSM on the Game Object).

The GUI is built from standard Unity components. The keypad is represented by the small box on the wall. When the player gets close enough it triggers automatically. This could be refined but works well enough for testing.

The Finite State Machine in Playmaker's editor window.

The Finite State Machine in Playmaker's editor window.

And here's the Finite State Machine (FSM) as depicted in Playmaker's editor. It starts in the 'Off' state. On entering the triggering state we progress to 'On'. This state handles drawing the GUI and also fires an event to the player controller to enter an 'interacting' state which freezes the player in place and enables the mouse cursor.

On pressing a number button a modified version of Playmaker's GUIButton class is called. This sets a string on a specified variable equal to that of the number of the button. We go to Error Check to see if the current value should be cleared, and, finally, append the number string to the code. On pressing OK we validate the entered code by comparing it to the correct version, and, if it's correct, we open the doors. We go to the Exit state from there so we can send an event to restore motion to the player and they can exit the area of the trigger. Once done, the FSM is reset and will trigger again if the player hits the trigger. If the code does not match, we update the display to show an error message and set a flag so we know to clear the display when the user presses another button.

There's some small improvements that could be made but, otherwise, this is working nicely. It's easy to modify and could be used in a number of places if required. Overall, it was a useful learning exercise and picking something slightly more complicated than a light switch forced me to learn a few different ways of using Playmaker.