Implementing Singleton Pattern in Unity

In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects. The term comes from the mathematical concept of a singleton.

Read more on Wikipedia

In Unity you need to create a scene that should be first scene in the Build Settings and make sure to run the game initially using this scene.

Now, you can add your Singleton components to the Game objects in the first scene, we call the first scene as Preload Scene, because it is loaded before loading any other scenes.

Also, you need to use DontDestroyOnLoad in the Singleton components to make sure they are persistent between scenes.

Now, if you run the game from Preload scene, and change scenes to other, you will only see one instance of these Singleton components, please note, that you shouldn’t load back to preload scene, otherwise the Singleton components will be duplicated.

You can find a good example of Implementation of Singleton at GitHub.

The Singleton pattern has many advantages, for example, you will have an object available for Global access, that Unity does not provides something similar by native.

This is how your Singleton implementation script should look like:

And here is a simple usage of the above Singleton implementation by a Component called GameManager:

And here is a test usage of the Singleton pattern by using GameManager instance:

Resources

Thanks for reading.

Hasan Bayat

Awesome Developer.

Leave a Comment

Your email address will not be published. Required fields are marked *