F:http://www.unitygeek.com/unity_c_singleton/
Objective :
Singleton is a very complex topic, In this, we try to understand basics and various implementation of
in Unity3d using C#.Intro:
Singleton is a basic Design Pattern. Classes implementing
pattern will ensure that only one instance of the object ever exists at any one time. It is recommend using Singletons for things that do not need to be copied multiple times during a game.This is great for controller classes like GameManager or AudioController.Implementation:
There are several ways of implementing
in Unity, we will some of the implementation in this tutorial- Simplest Implementation
Above code is the simplest implementation of Singleton, but there are some issues which we have to address
- Singleton is not persistent across the Unity scenes.
- All the executable code must be attached to GameObject in the hierarchy.
- It is not recommended to call Singleton
Controller.Instance
in anyAwake()
method because, since we don’t know the order that will be executed through all scripts, we can end up with a Null Reference Exception. - This code works only for SingletonController Class, but if you want another singleton controller eg. AudioController, we have to copy paste the same code to AudioController Class and do some minor changes to works, but this leads to .
Solution For First Issue:
This one is easy to fix, just add the DontDestroyOnLoad(gameObject)
Solution for Second and Third Issue :
For this issue we have to create the Singleton at the time it is required, means we have to lazily instantiate the SingletonController in Unity
Above code solves two different issues, it first searches for instance of
in the scene, If it doesn’t find a SingletonController component, a GameObject is created and a SingletonController component is attached to it, so with this it is not necessary for SingletonController to exist in the scene before hand, and this code will also destroy any additional copies it finds.As in this implementation we are lazily instantiating the Singleton, so now we did not worry about Null Reference Exception.
Solution for Fourth Issue : Generic Unity Singleton
The fourth issue was boilerplate code, so we need generic implementation of Singleton to solve this issue
So with this class we can make any class singleton, without duplicating the code. Just inherit your class from
and it ready to go.e.g
Conclusion:
Singleton is bit complex, but it plays very important role in game development. In complex game we may need many Singleton, so it is good to have a generic implementation of Singleton to reduce code duplication. Fourth solution deals with most of the issue.
I am happy to hear from you guys, Please share your view in the comment section.