Object construction with factory method

How to structure your code to produce loads of objects? Learn the Factory Method and how to implement it in Unity3d!

One of the most common things to do in making a game is instantiating objects at runtime. Be it bullets from a gun, enemies rushing forward or instances of software classes, sooner or later you’ll need to do it.

This is one of those classic problems of computer science that have been solved over and over again. The solution to it I’m going to talk about today is the Factory Method (not to be confused with the Abstract Factory, which is way more general in its application).

What’s a Factory Method?

factory-method-pattern

Basically it’s when you use an inherited method (either from a superclass or an interface) to create for you an instance of a Product. The Product will be set up just as you specified with the arguments that are given to the Factory Method.

For instance if you have an¬†EnemyFactory superclass, you could have a OgreFactory implement the FactoryMethod() for it. Then you could have an Ogre orc=datOgreFactory.FactoryMethod(100) to have orc‘s hit points set to 100.
Of course the GoblinFactory is another subclass of EnemyFactory but will still give you a 100 hp hulkling of a goblin if you ask for it with a Goblin hobGoblin=datGoblinFactory.FactoryMethod(100). It’s important to keep in mind that both Ogre and Goblin are one same kind of superclass: Enemy. This means they will share a common usage in their DieForLoot() function so that the kill procedure doesn’t need to know their specifics.

If you want a more technical definition, the internet is filled with it but I’d rather recommend to cut to the source and read it straight from the book written by the Gang of Four.

When to factory?

That’s more of a critical issue worth discussing. My personal answer would be to use it every single time you have more than exactly one thing to instantiate and most of the times you actually instantiate just one thing.

If you want dem clones, make a factory!
If you want dem clones, make a factory!

When you construct an instance of something twice, you are duplicating code and sure as hell it’s better not to write the same thing twice.

As for the reason I’d recommend to write one even if you are doing an instantiation just once:

  • if it’s something that will be a part of gameplay are you really sure you won’t be putting another one somewhere else?
  • Are you really sure you don’t need to test the instantiation itself indipendently?

Chances are, you will, and copy-pasting a bit of boilerplate code upfront is way better than refactoring after.

Also, it helps with respecting the single responsibility principle in the code: if instantiating that object was the only job of the class it’d be a factory, wouldn’t it?

But be careful: in some cases you might need to move even further and go full Abstract Factory. You might ask yourself:

  • Do I need to abstract everything or is it ok to work on concrete instances?
  • Do I need to hide my concrete code (i.e.: with a .dll)?
  • Do I need a factory of factories?

If you answered no to that, there’s no need for too much abstraction and you can just use the good old Factory Method.

blueprints-1837238_1920

How to build one in Unity3d

When working with Unity we have the usual problem of handling the references, which entails serious design decisions over how the factory should be realized. Plus in this case we have an additional issue: interface references won’t show up in the inspector, not even with a SerializeField .

Why? because just as generics (with the exception of the hardcoded List<T> ) interface references don’t get serialized in Unity, unless you write a workaround or pay sixty bucks …or at least five.

So this code:

public class FactoryUser : MonoBehaviour
{
    [SerializeField]
    IFactory thisWontSerialize;
    [SerializeField]
    MonoBehaviour factory;

will be rendered in the inspector like this:

immagine

So how to do a factory? Let’s begin with the interface (of course you can also make a superclass and skip half of the issues).

public interface IFactory 
{
    GameObject FactoryMethod(object[] parameters);
}

Why an array of objects? because we don’t know what we’ll need, so better have the thing that can do everything. A more type-safe approach would be to define a dedicated struct or class.

To have a working example we’ll implement a concrete factory that instantiates a number of childs of a main prefab:

public class ConcreteFactory : MonoBehaviour, IFactory
{
    [SerializeField]
    GameObject mainPrefab;
    [SerializeField]
    GameObject childPrefab;

First of all,¬† we add the references so that they can be seen in the inspector. Of course we’re going to make this class a MonoBehaviour, because to use the inspector is either that or ScriptableObjects and this is not a ScriptableObject tutorial. And I love the inspector.

inspector unity
He obviously prefers a platonic love ūüôĀ
    public GameObject FactoryMethod(object[] parameters)
    {
        GameObject mainObject = Instantiate(mainPrefab);
        int amount = (int)parameters[0];
        for (int i = 0; i < amount; i++)
        {
            GameObject childObject = Instantiate(childPrefab);
            childObject.transform.parent = mainObject.transform;
        }
        return mainObject;
    }

This is the method that implements the IFactory interface. What we now do is:

  1. Instantiate a copy of the main prefab.
  2. Dumbly take for granted that the first parameter really IS an int
  3. proceed to a runtime error to instantiate and reparent his child objects
  4. witness in horror as performance sinks since we didn’t use pooling here

Now that the concrete factory is done let’s see it in action:

public class FactoryUser : MonoBehaviour
{
    [SerializeField]
    MonoBehaviour factory;

Wait, why a MonoBehaviour reference? We don’t want any runtime checks, do we? This should be type-safe and checked at compile-time!

    public void OnValidate()
    {
        if (!(factory is IFactory))
        {
            Debug.LogError("Wrong reference type");
            factory = null;
        }
    }

Well, not really at compile time, we just need it to be done while the game isn’t running. So here’s a check that runs every time the field is modified in the inspector. Of course if you want to inject the factory instance or have it passed some other way, you can use an IFactory variable instead.

This is just a workaround to have both type-safety and serialization after all,¬†here’s another one if you don’t like it this way.

workaround unity interface serialization

But we’ll also avoid having to write a cast every time we use it:

    IFactory Factory { get { return factory as IFactory; } }

So we now can write:

    public void Start()
    {
        object[] parameters = new object[1];
        parameters[0] = 2;
        Factory.FactoryMethod(parameters);
    }

And finally, here it’s at work. Easy as pie. So easy it will be a pleasure to test and spam everywhere (provided you pooled everything).

Where’s the advantage of using this approach? Say your level designer wants to change the enemy type that is spawned in front of the castle gates, he can do it in the inspector simply by changing the factory that is referenced in the castle gate spawn component. No coding required, just a drag&drop.

That’s all folks!

Here’s a Unity project where you can grab al the code and see it in action, plus scroll down for a copy-pasteable version of it.

I hope you liked this tutorial, please tell me if you find this kind of guide interesting or not, either here or on my Twitter. If you don’t want to miss my next thing consider subscribing to my newsletter.

P.S.: I’m currently looking for a job, if you are interested here’s my portfolio.

public class ConcreteFactory : MonoBehaviour, IFactory
{
    [SerializeField]
    GameObject mainPrefab;
    [SerializeField]
    GameObject childPrefab;

    public GameObject FactoryMethod(object[] parameters)
    {
        GameObject mainObject = Instantiate(mainPrefab);
        int amount = (int)parameters[0];
        for (int i = 0; i < amount; i++)
        {
            GameObject childObject = Instantiate(childPrefab);
            childObject.transform.parent = mainObject.transform;
        }
        return mainObject;
    }
}
public interface IFactory 
{
    GameObject FactoryMethod(object[] parameters);
}
public class FactoryUser : MonoBehaviour
{
    [SerializeField]
    MonoBehaviour factory;
    IFactory Factory { get { return factory as IFactory; } }

    public void OnValidate()
    {
        if (!(factory is IFactory))
        {
            Debug.LogError("Wrong reference type");
            factory = null;
        }
    }

    public void Start()
    {
        object[] parameters = new object[1];
        parameters[0] = 2;
        Factory.FactoryMethod(parameters);
    }
}
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

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.

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

The singleton post – making a Singleton in Unity3d with inheritance

You already know what a singleton is? See how to do it by inheriting from a SingletonBehaviour<T>, skip to “How to singleton”

Sometimes when programming you are just reinventing the wheel. And by sometimes I mean all the time. Basically every problem a programmer faces is an already solved problem from an algorithmic perspective. Either that or you’d have better refused that job unless you are in academy.

So why not to look at all the already found solutions and use the ones matching your problem? The best solutions to the most common problems have been codified a long time ago, both for programming in general (ever heard of the Gang of Four?) and for game programming in particular.

Today I’ll¬†talk about one of these standardized solutions, the most famous one: the Singleton.

What’s “singleton”?

one-way-street-362172_1920

A singleton is a class that you want to make sure is unique and globally accessible.¬†This means that there’s only one in your scene and that it’s accessible from everywhere and everything.

Of course in Unity you won’t have a class floating in nothingness, althought you could do so with a static class. In Unity you want to use that sweet inspector to tweak the singleton’s variables, so you want to make it a component to an object.

When to singleton

gummibarchen-359950_1280

There’s a lot of cases in which a Singleton is just a good idea.¬†For instance since you only have one touch input source on a mobile device, it would be a good idea to have a singleton deal with it.

Also, if you are in need of managing the timing of all the enemy attacks in your musical shump a singleton would be the best candidate to handle the coordination. You need a lot of slowmotions and want to check if there’s overlap? Get a singleton to do that!

You should ask yourself these two questions to check if you need a singleton:

  • is this a thing that must not be duplicated or otherwise there could be problems?
  • is this a thing that I want to have easily accessible from everywhere?

When not to

Since the singleton is very quick to implement (and with this inheritance-based approach¬†you’ll need just a few characters to do so) it’s easy to over-use it and to add useless singletons.

An example is the case where you make a singleton EnemyManager and an Enemy¬†script, where the latter only has some data and the former’s only aim is to extend the Enemy¬†with methods. In that case is better to just add the methods in the Enemy script.

To check if you really need that singleton ask yourself:

  • do I need to hold some information in this class or it’s just methods?
  • can’t I just do the same things by extending something else?
  • will this raise my codebase’s coupling too much?

Also, since this is basically a global variable on steroids it goes without saying that if you have a problem with global variables you should use anything but this (i.e.: if you want to perform unit testing). In general a lot of people have a lot to object to the use of singletons, so inform yourself and make it your call.

singleton unity3d inheritance

How to singleton

[Notice: this part was written differently due to a buggy behaviour that now I can’t reproduce]

Since this is a design pattern you will find a host of different implementations of it and they will all be just as correct as this is, the real question is which way is more suitable to you.

In unity for instance if you use the singleton as a component in a GameObject you can be pretty sure that you won’t need to¬†bother with locks as they did in the unity wiki.

Also, I assume you aren’t trying to implement just one singleton class but that you’ll need a number of them and that you want to do it without duplicating code.

Well, its one kind of singleton inheritance, I guess...
Well, its one kind of singleton inheritance, I guess…

Given these assumptions here’s my implementation of it: we start with a generic class called SingletonBehaviour that inherits from MonoBehaviour, then whenever you want to create a singleton you just mark that class as inheriting¬†SingletonBehaviour.

Let’s look at the code:

public class SingletonBehaviour<T> : MonoBehaviour where T : MonoBehaviour
{

As I said this will be a generic class, that uses T as a parameter to indicate the actual type of the singleton we want to instantiate by inheritance. And that type will only be constrained to be a MonoBehaviour, so that only scripts that can be a component of a gameobject can be used for this.

    public static T instance;

This is where the references of our subclasses will be stored. Since it’s static only one instance per type is allowed.

Now let’s see what we do when an instance is created:

    public virtual void Awake()
    {
        if (instance != null)
        {
            Debug.LogError("Duplicate subclass of type " + typeof(T) + "! eliminating " + name + " while preserving " + instance.name);
            Destroy(gameObject);
        }
        else
        {
            instance = this as T;
        }
    }

The first thing to do is to check if this class has already been instantiated (notice, you can also use¬†if(instance)¬†if you don’t care for readability as you should), if that’s the case the GameObject is to be destroyed. Why the whole GameObject? Because this is a kind of failure so serious you want it to flash everything, add a Debug.Break()¬†too if needed.

For this tutorial’s purpose I’ve also added a (quite verbose) error message. Otherwise, we set the current class’ instance in the instance variable.

    public virtual void OnDestroy()
    {
        if (instance == this)
            instance = null;
    }

That is, only if the instance being destroyed is the same one being stored we go on and clean the contents of the instance variable.

So, now to use this one only needs to inherit from this class like this:

public class SomeSingleton : SingletonBehaviour<SomeSingleton>

Notice that¬†you are not enforced to use the same class as generic parameter by the compiler, which means that you could even have different classes compete for the same slot. I won’t recommend doing that on purpose: if you want to manage different singletons for one “slot” it’s best done explicitly instead of by relying on who gets there first.

That’s all folks!

Once again instead¬†I’ve built for you a test project so that you can download and test it in action, but of course down here comes also the copy-pasteable version.

I hope you enjoyed this tutorial, and that you will consider joining my newsletter. Please also tell me what you think of this and if you think I should cover more design patterns, either here or by hitting me up on twitter.

P.S.: I’m currently looking for a job, give a look to my portfolio if you are interested.

using UnityEngine;

public class SingletonBehaviour<T> : MonoBehaviour where T : MonoBehaviour
{
    public static T instance;

    public virtual void Awake()
    {
        if (instance)
        {
            Debug.LogError("Duplicate subclass of type " + typeof(T) + "! eliminating " + name + " while preserving " + instance.name);
            Destroy(gameObject);
        }
        else
        {
            instance = this as T;
        }
    }

    public virtual void OnDestroy()
    {
        if (instance == this)
            instance = null;
    }
}
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •