Getting rid of unnecessary singletons

I have often stumbled people using singletons for a lot of stuff when developing games with Unity. Most often they’re used for convenient access to all sorts of stuff like Game Managers, UI Managers, Game sessions handlers and Save systems. This is all fine and dandy for a while but as your code base grows longer you start to appreciate more loosely coupled code and maybe even do some unit testing.

Most Unity tutorials tend to always use public properties and/or FindObjectOfType to access other unity objects. However relying solely on these tends to make the code feel really messy and writing the same code to find certain object in the scene for the umpteenth time should ring DRY alarm for everyone.

However there’s a simple solution which is called the Toolbox which is at its core a static container class that just contains references to bunch of tools that you want easy access to from everywhere from your code.

The example in Unity3D wiki is all good, but in my opinion it’s a bit too complex to convey the basic idea behind a toolbox. So made a very stripped version with C# showing how you can make a simple toolbox to your game or software.

It’s a simple static class that uses public static properties with lazy initialization for tools.

public static class ToolBox
{
    static GameManager _gm;
    public static GameManager GM
    {
        get
        {
            if(_gm == null)
            {
                GameObject ob = new GameObject("GameManager");
                GameObject.DontDestroyOnLoad(ob);

                _gm = ob.AddComponent<GameManager>();
            }
            return _gm;
        }
    }

    static SaveSystem _saveSystem;
    public static SaveSystem MainSaveSystem
    {
        get
        {
            if (_saveSystem == null)
                _saveSystem = new SaveSystem("SaveData");

            return _saveSystem;
        }
    }
}

With this you could access your GameManager and SaveSystem from anywhere simply anywhere in your code like like this:

ToolBox.GM.ResetGame();
ToolBox.MainSaveSystem.SaveGame();

This should be much cleaner and more loosely coupled than relying on multiple singletons. None of the tools themselves are singletons so if you for some reason need a dozen game managers in your game in future (e.g one for each player) you can do that.  You could also change any of the tools with different versions without having to modify code elsewhere, provided that the versions contain the same methods or the same interface.

One thought on “Getting rid of unnecessary singletons

Leave a comment