Adding Cheats and Features to a Unity Game for Development Only

January 22, 2016

I’m currently writing a breakout style game (which, if you’ve seen any of my previous posts, you might have divined). One of the things that I would like to do with this, without having to play through all the levels is to complete the level quickly. This led me down the path of creating a “Cheat” button. However, for those amongst you that remember the ZX Spectrum, the makers of Jet Set Willy may have had a similar idea, but left the “Pokes” in the final game.

To avoid this, I thought it must be possible to use a feature such as the compiler directive in C#. In fact it is. Unity has its own, and one is to determine whether you’re running in the editor.

Here’s how I conditionally display the button:



    void OnGUI()
    {
#if UNITY\_EDITOR
        if (GUI.Button(new Rect(10, 30, 50, 30), "Cheat"))
        {
            var o = GameObject.FindGameObjectsWithTag("Brick");
            foreach (var b in o)
            {
                var r = b.GetComponent<Rigidbody>();
	        r.transform.position += new Vector3(0, 0, zOffset);
                r.useGravity = true;
            }
        }
#endif
    }

This particular cheat just makes all of the bricks fall out of the sky. UNITY_EDITOR is one of a list of pre-defined “Platform Defines” that can be found here.



Profile picture

A blog about one man's journey through code… and some pictures of the Peak District
Twitter

© Paul Michaels 2024