The singleton follow-up – a deeper look into singletons in unity3d

This post it’s a bit different than usual. This is not just a tutorial but rather “the talk”… or a grownup discussion depending on your degree of advancement. And yeah, for some of you it’s going to be like “Look kiddo, I’ve been doing this shit long before you even saw your first keyboard”, for those of you, I’m sorry, I hope this won’t be extra cringy and just jump to the “What’s the solution?” paragraph.

We’re now going to discuss a little bit of architecture, or as some of you were thinking in last post “why singletons can break everything for everyone”.

sex-talk-kids-know-more

The reasons behind

Up until now maybe you thought that the problem is doing stuff with code, hitting up on the keyboard until the pixels behave properly, but hacking a system until it does what you want with the least possible effort is the aim of all of us, including those of us that are seen using some more exoteric stuff like zenject.

The thing is: not everyone deals with the same time horizon. If you are just doing a short game jam, a single megalithic script with all your code in it could even be a good idea (i.e.: if your problem is writing fast enough and alt-tabbing it’s too slow for you).
But let’s say you are going to develop a project that’s going to stay 10 years, better believe that spending one month just planning ahead may not be enough. And if you are using an engine, with a 10-yr horizon you could bet that maybe not even the engine is going to stay all that time. The engine developer may shut down and you may have to change it 6 years from now for all you know.

So in some cases you just need to plan for maintenance a lot and do stuff that it’s not that immediate because of issues that would come up only a few years into development.

afterburner-inspection-897513_1280

How in hell are singleton involved?

The thing is, when I think singleton in unity, I think static class with an inspector. This is since the other ways to use singletons have quite serious issues that a long term project cannot ignore. And by the way, even that won’t be good in many cases.

The most important issue here is maintenance. Maintenance cost is sometimes so high that it’s just cheaper to throw everything away and build it from scratch again. And for maintenance there’s an important concept that every dev should tatoo on his right arm memento-style: dependency management.

When class A uses class B, A depends on B meaning that if you make changes to B you are going to have to change A too.

This doesn’t render justice to the issue. Let’s put it another way:

In a project where every class depends on every other, just change one function and you’ll have a fun time rewriting almost all of it.

And what do singletons have to do with this? As I said in last post, they are basically a global variable on steroids, so they put hidden dependencies in your code. This means:

In a project where every class hiddenly depends on every other, just change one function and you’ll discover by surprise that you now must have a fun time rewriting almost all of it.

So when you plan your architecture you better mind it and ask yourself “how is this class going to affect the others when I change it?”

that's quite unstable
that’s quite unstable

Instantiation issues

One of the big problems with singletons is their instantiation (or rather, the dependencies it entails). Who instantiates a singleton and when? If you do it like I’ve shown in my last tutorial, you’ll leave that to unity by just putting a GameObject with a component in your scene and keep it there forever. But the singleton pattern allows for a host of other solutions.

Another solution is called Lazy loading, which means that you load the singleton when is first used, something like this [DANGEROUSLY WRONG EXAMPLE]:

public class LazySingleton {
    static LazySingleton instance;
    public static LazySingleton Instance 
    {
       get 
       {
          if (instance  == null) 
          {
              instance = new LazySingleton();
          } 
          return instance;
       }
    }
}

Now, with current Unity implementation and without ever thinking of multi-threading that may not sound too much of a problem. But let’s say that 4 years from now they go on hard on multi-threading (or that you just don’t want to waste those many extra CPUs), then you won’t know if two classes that try and access the instance get the same one or not.

Why you don’t know? because they might both do the if (instance==null) at the same time and therefore get two instantiations done. You therefore have to lock your code and make it thread-safe.

Loading time(s)

Using MonoBehaviour and putting it on a GameObject in your initial loading scene takes this issue away from you, but still leaves one window open for troubles: what if you want to use that singleton in one of your Awake functions in that same scene?

If you remember my Event System tutorial that’s one issue that could require quite extreme solutions, but there is a more general issue here that is explained in Sebastiano Mandala’s blog better than how I can do here in a few words.

Let’s just say that Unity hides away a quite crucial step: the code’s entry point. You’ll never have the pleasure of being sure that the row X of the class Y is really the first thing that’s executed, at least not by just looking at the code. You’ll have to tamper with Script Execution Order settings, hope the next update won’t screw it up, do it every time you want to import your code base on a new project, hope it’s bug free.

Spoiler: that’s bad.

455252569_7b5bcdff02

What’s the solution?

So, we’ve come to understand that what’s bad in singletons is (mainly) two things:

  • they hide dependencies
  • they need to be instantiated carefully

About the hidden dependencies, that’s more than anything a matter of implementation inside your singleton: if you make it so that his state needs management and coordination across its users, that’s where the hidden dependency creeps in. And that’s the symptom of a bad design. If that is the situation you are in, consider using command pattern and having another class manage explicitly the singleton’s state, so that the users can just make a request without needing any coordination among each other.

While the hidden dependency is a universal problem, the instantiation is quite hard to manage in Unity. Luckily there are solutions. Yeah, plural. Which means there’s no best and safest here, I’ll highlight just two of them, but I encourage to seek for more (and to write about it in the comments if you want to share).

ragecomic

Option A: automate everything

One solution is to take away from Unity the control and go all in with frameworks like the aforementioned Zenject or Svelto.ECS.

What it does is to manage for you the instantiation of classes, of course you need a solid understanding of what Inversion of Control and Dependency Injection are and why they’re needed or you’ll end up in a horrible mess, but on the other side you get to have your code layout practically already decided with a safe and sound architecture that’s Unity-independant. This will also enable you a lighter maintenance process.

On the con’s side there’s now a framework running in the background that will consume resources, will cache information and generate garbage without you even noticing. In these conditions keeping up with memory budget gets harder, in some cases this is therefore just not an option. Also, readability of your code takes a hit, since now you must mind unwritten implications of using a reference and since the system forces you to make a bit more boilerplate code.

In this solution you just don’t use singletons because you don’t need them. You already have global access to services (the framework does it for you) and as for uniqueness you can just use a static class.

art-1837073_1280

Option B: handcrafting

One other solution is to carefully think about dependencies and manually manage instantiations (AKA filling the dependency graph). This means again to take away control from Unity, but by using the tools that it gives you. This also means that you just define an entry point for your code (for instance by using a dedicated scene that gets loaded for first) and use a dedicated script to manage all the objects’ instantiations, so now the singleton doesn’t manage his own instantiation, it just wards off against duplicates.

This has of course the big advantage of readability: everything is laid down clearly in your code, nothing stays hidden any more and you know what gets done when. Another big plus is performance, since you are in charge of doing everything you can put that extra care in it to avoid wasting a single bit.

The problem here is that now you are in charge, there’s no standard to protect you from bad decisions. Maintenance gets a bit harder and if you work in a team it requires surveillance to check that no-one caves in to deadline pressure and starts cutting corners. It also means that you will have to plan ahead and consider the implications of your design, wich means time shall be devoted to this.

In this scenario you can use singletons but you’ll have to care for everything and be mindful of the risks they carry. Again, my approach here is to think static class with an inspector, but the good way to go may also extend further, you just need to remember that a singleton is no excuse for not abstracting what can be and not to follow the SOLID and IoC paradigms.

keep-calm-and-hakuna-matata

 

Some non-problems

Sometimes I also heard as an argument against singletons something along the lines of : “it breaks solid because it has to deal with its own instantiation, which by definition violates the Single responsibility“. Now, technically, that’s undeniably true. Practically it isn’t. The only reason we’ve got to write boilerplate code to get a singleton is because this is not a feature of the language.

If we were in a world where static classes were not a thing and only static fields existed, to create a static class would imply some tinkering, just the same way. Would that violate the single responsibility? Abso-fucking-lutely. Would anyone argue that therefore we shouldn’t use static classes? probably someone, this doesn’t mean we should consider it a good reason not to use static classes.

If you decided to have a singleton, that’s on the same level of deciding to have a static class. The only difference is that you can’t do it with just one word in your language. The real issue is when you instantiate it, but that procedure is not what makes a singleton a singleton. You can delegate instantiation to another class and only check for uniqueness in the singleton itself (something that you wouldn’t need to do if there was a language keyword). If someone doesn’t delegate this responsibility on another class, is not due to the pattern but to implementation.

Another quite widespread criticism is that singletons carry state around the application’s lifetime and that makes automated testing harder. Again, this is undeniably true: they do carry state and state does make tests harder.

But the thing is that it’s not just singletons that have this issue! You would get this problem with any interaction with external components that just don’t always give every single time the same result. So except for pure functions you already deal with this for all external dependencies you have in any class.
Also, if you have given the singleton a state it’s probably because you needed to represent something that will still need a stateful representation even if implemented elsewhere.
You’ll therefore get the same result with any other pattern in terms of testing problems.

So, why I did it that way?

Now it should be more apparent why I picked that specific design to implement singletons within Unity:

  • inheriting from MonoBehaviour delegates the instantiation to the engine, so no thread-safety measures and locks are needed
  • making it a component of a GameObject enables to use the inspector, which means a designer can tweak the parameters
  • using Awake to initialize the reference leaves room for other classes to use it on Start
  • creating a class from which to inherit the singleton-ness helps to keep different responsibilities in different files and enhances readability

In other words, although I didn’t use a great deal of Unity’s features, it’s a very Unity-dependent code in its design.

And by the way, if you don’t make the instance variable publicly accessible and write all your public functions as static functions that access the instance, you’ll really basically get a static class with an inspector.

public class StaticWithInspector : MonoBehaviour
{
    static StaticWithInspector instance;
    public static StaticWithInspector Instance
    {
        set
        {
            if (instance == null)
            { instance = value; }
        }
    }

    void reallyDoIt() { }

    public static void DoSomething() {
        instance.reallyDoIt();
    }
}

See? here we have it, the Instance property allows to check for uniqueness and the usage will be exactly the same of a static class. Of course you can use this in combination with the script of the last time.

That’s all folks!

I hope that in this post there was something of value even if this time there was no script to grab. Last tutorial left so much untold that I felt the need to write about it. I’ve also received a lot of useful feedback, wich by the way has shown me that there’s interest even in something that’s not just a basic coding how-to.

Special thanks go to Sebastiano Mandala’, Christian Meneghini, Claudio Freda and Lars Kokemohr for their remarks.

As usual, if you want to keep up with my stuff, consider registering with my newsletter. For any comments discuss down here or hit me up on Twitter.

P.S.: I’m currently looking for a gamedev job, if you are interested have e look at my portfolio.

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Event system: tutorial for Unity3D & C#

  • Part 1: basics event system [you are here]
  • Part 2: event picker drawer for in-editor usage
  • Part 3: debugging with platform dependant compilation
  • Part 4: multiple dispatchers
  • Part 5: optimization

Today I’ll start presenting you the single most useful piece of code that I’ve ever written. Since writing it I used it in every single project I’ve made, however simple. Even in game jams.
I’m speaking of an Event System. A class with no other purpose than to let other objects communicate with each other, with as little overhead as possible. And it’s implemented with delegates.

And it’s way better than SendMessage, if you ask me.

event_driven_programming

What’s an Event System?

Those of you who already know, just skip this paragraph. Still with me? good. The main problem you’ll have with SendMessage is that it needs to use a method’s name as an input. So the object sending the message not only needs to know what method should be invoked by the receiver, but also his name. In a case sensitive way. Want to change that name? too bad, the IDE won’t change the string for you. You’ll have to remember every single one of those and do it by yourself… or never change a function name ever again. Or remove one.

Sounds bad? it is. It’s a maintenance nightmare. Plus, it uses strings. Fuck strings. Strings are evil. They use your memory, trigger your garbage collector and spit on your mother. Never use them unless at gunpoint… and even then think twice about it and instead use an enum.ToString() if you can.

So what’s the solution? we need something more like this: you need to send a message between objects (or scripts) when a “thing” happens. So the scripts in the other object react to the “thing”. The caller script doesn’t need to know who or how will do anything in reaction to the “thing”. It just needs to shout out “Hey! I have a thing here!” and eventually how big the “thing” is. For instance, “Hey! I have a 3.5 Damage here!”. Then the health script subtracts the damage and the particle script spills blood everywhere. But the collider doesn’t need to know that. The “thing” is an Event. Shouting is a Broadcast. The reactions are called Callbacks or Handlers.

But this is nothing I invented, you can just study it here or here, or even here.

What’s a Delegate?

As before, if you know already, just skip ahead. Delegates are something I wish they did teach me in university, because they are just awesome. To put it bluntly: in C# you can treat functions as if they were variables and pass them as an argument to other functions. This means that you can change behaviours of an object at runtime. Or have an object hold and call a function without it even knowing what it does. Absolute decoupling. A maintenance heaven.

Before you can use a delegate, you first need to declare its type. Which means telling the compiler which return type and what arguments will be assigned to it. Not its name. Not its content. Just the signature structure. Of course, if you use as a signature something like:

public delegate object nameFunct(object o);

you can then pass anything and get anything (but say goodbye to compiler type-checks).

After you have declared a delegate type, you can then declare a delegate variable and assign to it a function with a matching signature. Just like you would do with any other variable. If you still need to delve deeper you can go here or here.

Get on with it!

gowi-2

Now, if you have seen my portfolio the event system there can be quite intimidating, but don’t worry, we won’t be doing that version right now. We’ll start with version 0.0.3 while that one is 1.0.1 [edit: this was before optimizing for the last part of the tutorial]. That makes about 100 rows of code and 20 headaches of difference.

Before we get to the main class, the event dispatcher, let’s define some stuff we’ll use there.

public delegate void gameEventHandler(eventArgExtend e);

This will be our event signature. Nothing to return because we don’t want the event sender to have anything to do with the receivers. The event type is this thing here:

public class eventArgExtend : System.EventArgs { }

Why didn’t I use directlySystem.EventArgs? Because in the future I may want to add something between those parentheses and when it happens it will cost me nothing to do so. Had I used directly that type it could require more work to do it.

Now, let’s get to something more interesting: defining the events themselves. To do so I’ll use something infinitely superior to strings: enums.

public enum eventChannels
{
    inGame
}
public enum inGameChannelEvents
{
    thing
}

Now we’ll need a comfortable way to pass this information to the dispatcher. For this I just created a class with a static function:

public class ChannelEnums
{
    public static Dictionary<eventChannels, System.Array> getChannelEnumList()
    {

        Dictionary<eventChannels, System.Array> enumChannelEventList = new Dictionary<eventChannels, System.Array>();
        enumChannelEventList.Add(eventChannels.inGame, System.Enum.GetValues(typeof(inGameChannelEvents)));
        return enumChannelEventList;
    }
}

Notice: adding a channel requires to add a new enum type, and there is no automated way to set a link between an enum value ineventChannelsand an other enumtype. So for each channel you need to add, you’ll have to write a new row of code like the one just before thereturn.

What we did here is to create a static function for the dispatcher. The function will recovery every event channel and every corresponding array of values, so that we can initialize the list of listeners in the dispatcher. All in the nice form of a Dictionary.

Now let’s get to the Event System

Our event system needs to be usable at EVERY stage of game play. This includes the Awake function of the first objects to be present in the first scene. Which means that I can’t use the Awake function to initialize the event system, or I would get in a race condition. That’s fucked up. But years of Unity3D ninjutsu allowed me to discover a precious thing: default values are initialized before Awake, and you can get them with static functions.

public class eventHandlerManager : MonoBehaviour
{
    static Dictionary<eventChannels, Dictionary<Enum, gameEventHandler>> ListenerFunctions = initializeDicts();

What’s thatinitializeDicts? we’ll see later. For now just look at the type of ListenerFunctions: it’s a dictionary of dictionaries. It allows us to index gameEventHandler delegates first by channel and then by event.

Now we can write the key functions of the dispatcher: one to raise an event, one to add a delegate as listener, one to remove it.

public static void Broadcast( eventChannels evType,Enum ev,eventArgExtend e) 
	{
		ListenerFunctions[evType][ev](e);
	}
	
	public static void AddListener(eventChannels evType,Enum ev, gameEventHandler eventListener)
	{
		ListenerFunctions[evType][ev]+=eventListener;
	}
	public static void RemoveListener(eventChannels evType,Enum ev, gameEventHandler eventListener)
	{
		ListenerFunctions[evType][ev]-=eventListener;
	}

Why are they all static? because that way you don’t need to get the other classes to find the instance. Yes, this is limiting: you can’t have a damage event that only gets notified to one character. But for something more selective we’ll need to make a lot of changes, for the time being just add an identifier as field in the argument. Then have the receivers check that value. We’ll get back to that in future tutorials.

This is all that’s needed on the outside to use this event handler. Other classes that want to react to an event just need to declare a function that matches thegameEventHandlersignature and then invoke theaddListenerfunction giving that function as the last argument (without parentheses), and do the same for removal like this:

eventHandlerManager.AddListener(eventChannels.inGame, inGameChannelEvents.thing, onThing);

The broadcast use is even simpler:

eventHandlerManager.Broadcast(eventChannels.inGame, inGameChannelEvents.thing, new eventArgExtend());

So, now we’re almost done. There is just one last detail for the magic to fully work: how do we initialize and cleanListenerFunctions?

    public void OnDestroy()
    {
        ListenerFunctions = initializeDicts();
    }

    static Dictionary<eventChannels, Dictionary<Enum, gameEventHandler>> initializeDicts()
    {
        Dictionary<eventChannels, Array> enumChannelEventList = ChannelEnums.getChannelEnumList();
        Dictionary<eventChannels, Dictionary<Enum, gameEventHandler>> result = new Dictionary<eventChannels, Dictionary<Enum, gameEventHandler>>();
        foreach (var val in (eventChannels[])Enum.GetValues(typeof(eventChannels)))
        {
            result.Add(val, new Dictionary<Enum, gameEventHandler>());
            foreach (var ev in enumChannelEventList[val])
            {
                result[val].Add((Enum)ev, new gameEventHandler(delegate (eventArgExtend e) { }));
            }
        }
        return result;
    }

Wait a minute: did I initialize ListenerFunctions on destroy? Yes, because that is a static field. It will survive to the existence of the eventHandlerManager instance. And since that should only happen on a scene load, I can be sure that nothing should stay in the dictionary and that the new scene has a ready new clean slate to work on when the first Awake is called.

The initialization works by first getting the enum data from the static function we defined before in ChannelEnums, then using that data to initialize every field of the dictionary with an empitygameEventHandler; this way we can later add the Handlers with a+=instead of checking for a null field every time.

That’s all folks!

Not really. Actually there is a lot more that we can add to this class, mainly for debugging purposes, plus the “local” version of the event dispatcher that I mentioned before. But this tutorial is already huge, so maybe it’s better to deal with that stuff next week. If you want to be sure not losing it, subscribe to my newsletter. For any feedback comments are below or you can just add me on twitter.

using System;
using System.Collections.Generic;
using UnityEngine;

public class eventHandlerManager : MonoBehaviour
{
    public static Dictionary<eventChannels, Dictionary<Enum, gameEventHandler>> ListenerFunctions = initializeDicts();

    public static void Broadcast(eventChannels evType, Enum ev, eventArgExtend e)
    {
        ListenerFunctions[evType][ev](e);
    }

    public static void AddListener(eventChannels evType, Enum ev, gameEventHandler eventListener)
    {
        ListenerFunctions[evType][ev] += eventListener;
    }
    public static void RemoveListener(eventChannels evType, Enum ev, gameEventHandler eventListener)
    {
        ListenerFunctions[evType][ev] -= eventListener;
    }

    public void OnDestroy()
    {
        ListenerFunctions = initializeDicts();
    }

    static Dictionary<eventChannels, Dictionary<Enum, gameEventHandler>> initializeDicts()
    {
        Dictionary<eventChannels, Array> enumChannelEventList = ChannelEnums.getChannelEnumList();
        Dictionary<eventChannels, Dictionary<Enum, gameEventHandler>> result = new Dictionary<eventChannels, Dictionary<Enum, gameEventHandler>>();
        foreach (var val in (eventChannels[])Enum.GetValues(typeof(eventChannels)))
        {
            result.Add(val, new Dictionary<Enum, gameEventHandler>());
            foreach (var ev in enumChannelEventList[val])
            {
                result[val].Add((Enum)ev, new gameEventHandler(delegate (eventArgExtend e) { }));
            }
        }
        return result;
    }
}

public enum eventChannels
{
    inGame
}

public enum inGameChannelEvents
{
    thing
}

public class eventArgExtend : System.EventArgs { }

public delegate void gameEventHandler(eventArgExtend e);

public class ChannelEnums
{
    public static Dictionary<eventChannels, System.Array> getChannelEnumList()
    {

        Dictionary<eventChannels, System.Array> enumChannelEventList = new Dictionary<eventChannels, System.Array>();
        enumChannelEventList.Add(eventChannels.inGame, System.Enum.GetValues(typeof(inGameChannelEvents)));
        return enumChannelEventList;
    }
}

 

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Server maintenance gold

From:
http://meta.serverfault.com/questions/1986/what-are-the-canonical-answers-weve-discovered-over-the-years

These are the questions we have identified as Canonical:

Capacity Planning

Career

Datacenter Design

Documentation

EMail & Spam

Hardware

Hosting provider/server hardware shopping

Infrastructure Software

Licensing

Networking

Security

SSH

Terminal Server (RDS)

Uptime

Virtualization

Web Servers

Windows (General)

Meta

List of Canonical Topics that do not have a Q/A yet or need improvement:

Career

Datacenter Design

Infrastructure Software

Networking

Web Servers

  • Apache vHost
  • Apache .htaccess/overrides

Enterprise Storage

Create one or more Question that covers “ES” topics… not sure how this should be organized exactly. Merge these answers into that Question(s) (keeping them separate/complete answers).

Server Hardware

In response to Why The Hostility, I wrote this for consideration as a canonical Q/A:

What are the basics of running a Web Server?

my.cnf generation wizard:

https://tools.percona.com/wizard

Database table fragmentation command:

mysqlcheck -u root -p –auto-repair –optimize –all-databases

Ultimate Guide: Stop and Remove All the Spam and Other Junk Traffic in Google Analytics

Ultimate guide: How to stop and remove ALL the spam and other unnecessary traffic in Google Analytics

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •