Implementing Cheat Codes

Cheat codes are secret ways to alter the functionality of a game.  It's a term that makes me cringe as a parent, since we teach our kids never to cheat — but once a game starts to grow complex, cheat codes are absolutely essential testing tools.  They let you bypass minutes or hours of gameplay you already know is working, in order to get to the part you're trying to fix.

So, how do you actually implement them?  This post explains how we do it in our Unity games.

First, you need to decide what form the cheat code will take.  In a game that's played primarily with the mouse, such as Chesster, it's convenient to use; simply typing a magic word can cause the effect.  In a tablet game you could instead use a sequence of taps in special places; in a console game, you might have to use a special series of button or directional inputs.  But for the sake of this post, let's assume you have a keyboard (as you always will when testing within the Unity editor anyway).

An easy way to detect any keypress is to watch for KeyDown events in the OnGUI event.

void OnGUI() {
        if (Event.current.type == EventType.KeyDown) {
            HandleKey(Event.current.keyCode);
        }
    }

This simply detects the keypress, and passes it off to a HandleKey method, whose job it is to process these key events and collect a complete input string.

    void HandleKey(KeyCode key) {
        if (key == KeyCode.None) return;
        if (key == KeyCode.Return || key == KeyCode.KeypadEnter) {
            // Enter/Return: process (and clear) the input
            ProcessInput(inputSoFar);
            inputSoFar = "";
        } else if (key == KeyCode.Escape) {
            // Escape key: cancel/clear the input
            inputSoFar = "";
        } else if (key == KeyCode.Delete || key == KeyCode.Backspace) {
            // Delete/backspace: remove the last character of the input
            if (inputSoFar.Length > 1) inputSoFar = inputSoFar.Substring(0, inputSoFar.Length-1);
        } else {
            // Anything else: add the character to our input string
            string c = key.ToString();
            if (c.StartsWith("Alpha")) c = c.Substring(5);
            inputSoFar += c;
        }
    }

Notice that we process backspace (and delete) to allow for simple typo correction, as well as the Escape key to cancel it, and Return/Enter to actually submit the input.  The "else" block above handles all the regular characters, using the name of the key as defined by Unity.  For alphabetic characters, this is just the letter itself: "A", "B", etc.  Numbers (on the main keyboard) come through as "Alpha1", "Alpha2", etc., so we strip off the "Alpha" part and keep just the number.  The result of all this is that you can type something like "JOSHUA5" as one of your cheat codes.

So all that's left is actually doing something when a cheat code is entered!  This happens via another custom method, ProcessInput.  In most cases I prefer to have each cheat code simply invoke a UnityEvent. So at the top of my CheatCodes script, I'll have things like:

    public UnityEvent unlockAllGems;
    public UnityEvent lockAllGems;

And then my Process Input method simply does a big switch on all the various cheat codes, and invokes the appropriate one.

    void ProcessInput(string input) {
        Debug.Log("Cheat code input: " + input);
        if (input == null) return;
        switch (input) {
        case "ALLGEMS":
            unlockAllGems.Invoke();
            break;
        case "NOGEMS":
            lockAllGems.Invoke();
            break;
        default:
            Debug.LogWarning("Unknown code: " + input);
            break;
        }
    }

That's it!  Put all this together in a "CheatCodes" script, and then attach it to any convenient object in your scene.  Better yet, make a new object for it, also called Cheat Codes, so you can see at a glance whether it's enabled.  The Unity events provide a clean separation between the cheat code processor, which knows nothing about your game; and the game code, which knows nothing about cheat codes.  Whether you make the cheat codes available to players in the final game is up to you!