Design Pattern: Singleton

The Singleton is one of the most famous programming patterns, it is also used with Unity, it is a creative design pattern that aims to ensure that one and only one instance of a given class is created, and to provide a global access point to that instance.

there is more than one way to use this design pattern we will see some of them now but let’s start with its implementation.

We are going to create two static variables with the same name as our class. The private one will be the variable accessible only within the class and the public one using a property that will ensure that we can access it only for reading. This will allow us to access the methods and the public variables of this class.

In the construction of the property, we are going to insert the control to verify that the class exists.
If the class doesn’t exist we can decide to create it, this can be a solution for classes that don’t need external elements like a prefab to instantiate at runtime.

Usually, we add this design pattern to all classes that need to be reachable from other classes without having to use the GetCompoenent call every time.

An alternative can be to create a class for the singleton and make it inherit from the classes that we want to have this peculiarity.

It is necessary to remember that we are in Unity and that the singleton class must inherit from Monobehaviour, also because in c# there are no multiple inheritances but we can inherit only from one class.