Monthly Archives: January 2016

Adding Cheats and Features to a Unity Game for Development Only

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.

Saving and Loading Level Data in Unity

This describes a method of persisting data in Unity. For example, saving and loading the current game level.

The first thing that you will need is to create a helper class to read and write the data that you need:

        public static void SaveGameState()
        {
            XmlDocument xml = new XmlDocument();
            var el = xml.CreateElement("PlayerStatus");
            el.SetAttribute("CurrentLevel", Application.loadedLevel.ToString());
            xml.AppendChild(el);
            xml.Save("data.xml");
        }

        public static void LoadGameState()
        {
            XmlDocument xml = new XmlDocument();
            xml.Load("data.xml");
            var el = xml.GetElementsByTagName("PlayerStatus")[0];
            string currentLevel = el.Attributes["CurrentLevel"].Value;
            int loadLevel = 0;
            if (!string.IsNullOrEmpty(currentLevel))
            {
                loadLevel = int.Parse(currentLevel);
                if (Application.loadedLevel != loadLevel)
                    Application.LoadLevel(loadLevel);
            }
        }

The next stage is to plug this into Unity. I put the following in a Master Script (which is essentially just a script associated with an empty game object).


    void OnApplicationQuit()
    {
        GameState.SaveGameState();       
    }

    void Start()
    {
        GameState.LoadGameState();
    }

I’ve seen plenty of articles on using serialisation for this, and that would obviously have the same effect, but this is another option.

Using inheritance in Unity for better code re-use

In previous posts regarding Unity, I’ve made the comment that I’m quite new to Unity… but I’m not new to C#, and have been a little surprised regarding the apparent lack of code re-use through inheritance and polymorphism in scripting examples that I’ve seen. So much so, that I started to assume that, for some reason, this wasn’t possible in Unity.

It is. I was looking for an architecture like this:

UnityArchitecture

As an experiment, I created a base script:

public class BaseScript : MonoBehaviour
{
    public virtual void RunStart() { }
    public virtual void RunUpdate() { }

    void Start ()
    {
        RunStart();
    }
	
    void Update ()
    {
        RunUpdate();
    }

    void OnCollisionEnter(Collision collision)
    {
        StandardCollision(collision);
    }

You get the idea. I handle the standard functions, and then provide either some default functionality, or none, and allow the child to override. Inherit as you would for any base class:

public class MyScript : BaseScript
{
    public override void RunStart()
    {
        base.RunStart();

As you would expect from any C# / .NET similar structure, you reference in the child script, and you get the base functionality.

Playing a longer running animation in Unity

Continuing on with my list of things that I’ve found in unity (I’m using 5, but have no reason to believe these wouldn’t work for 4), I had cause to execute an attack animation in a character. For reference, the character I’ve been using is here

So far, when playing an animation, I’ve used something similar to this:

gameObject.GetComponent<Animation>().Play("Idle_2");

In fact, if you put that in the Update of the linked object, you’ll get an angry looking chap looking like he’s about to charge. In order to plumb in the attack, it’s necessary to cache the animation. Start with a class level variable:

private Animation _animation;

Then, inside the update statement, something similar to this:

void Update ()
{
    if (_animation != null && _animation.IsPlaying("Attack_1")) return;

    if (Input.GetKeyDown(KeyCode.Space))
    {
        if (_animation == null)
            _animation = gameObject.GetComponent<Animation>();
        _animation.Play("Attack_1");            
    }
}

One of the bizarre things that I learnt about unity while doing this, was that if you have a null reference, it doesn’t crash. It doesn’t work, but it doesn’t crash.

I find this annoying.