Unity: Singleton pattern … yes or not?

In the next blog I will try to explain what is a Singleton pattern, what are the advantages, disadvantages and I will give you an example of how use it.

1. What is a Singleton pattern?

With the singleton Pattern you can ensure that your class is unique in your project and in the same time you make it accessible globally.

2. Advantages of using the Singleton pattern

Well, this pattern have some advantages like the fact that is globally accessible, can be used to save data (and when you combine with DontDestroyOnLoad it can pass the information it from scene to scene).

It’s a useful pattern, but sometimes developers abuse it, that’s what makes some love it and some hate it.

3. Disadvantages of using the singleton pattern

There are many disvantages of the singleton pattern, one of them are the rigid that your code can become if you use it in the wrong way. For example, everytime that you make a changes in your singleton this will affect the others scripts that depends on it.

Another disadvantage is the that can only exist one singleton of each class at the sametime, which indeed is not much problem if you know what you are donig, but also make the necesitie to check if there is another script singleton of the same class to destroy it, aiming to respect the rule of one and only singleton of each class.

4. Uses of singleton pattern

The uses of the singleton pattern are always the same: save values of variables.

And is the why, many people use it like game manager or music manager or other kind of “manager” with the objective of store values and use that values in others scripts.

5. Here is a example of a singleton pattern

This example of a singleton patterns is copied from this blog https://www.patrykgalach.com/2019/04/04/singleton-in-unity-love-or-hate/

In that blog they explain how to use it and some variables when writing the scripts of a singleton pattern.

6. Remember nothing in excess is good, even the singleton patterns

In the upper image (a joke) you can find why some developers does not like this pattern. And that is because some other abuse of it and create a singleton pattern for everything, creating a scripts interdependent which in the last create a very hard code to refactorize.

If you find this blog useful let us a comment, and follow us in our Instagram @tortugamedev and Twitter @Totuas2.
And don’t forget to check out the rest of the blogs!!

Leave a Comment

Your email address will not be published.