Singleton mode is one of the object's creation patterns, guaranteeing that a class has only one instance and provides a global access point to access it.
Under what circumstances is a singleton used:
1, some manager classes. such as voice manager, scene manager, User Manager, etc.
2, some auxiliary functions.
Unity in the single implementation is divided into two, one is inherited from the Monobehavior, the other is a common singleton, where the use of multithreading is not considered, in the creation of a single case is strictly in accordance with a certain order to create, and then in reverse order to destroy.
A single example that inherits from Monobehavior:
Common Single case:
usingSystem; Public classSingleton<t>whereR |New(){ Public StaticT Instance {Get { returnSingleton<t>. _getinstance (); } } Public Static BOOLexists {Get { return!Object. Equals (Singleton<t>._instance,default(T)); } } Private StaticT _getinstance () {if(Object. Equals (Singleton<t>._instance,default(T))) {Singleton<t>._instance = activator.createinstance<t>(); } returnSingleton<t>. _instance; } protected StaticT _instance;}
Monobehavior Single case:
usingSystem.Collections;usingSystem.Collections.Generic;usingUnityengine; Public classMonobehavioursingleton<t>: MonobehaviourwhereT:monobehavioursingleton<t>{ Public StaticT Instance {Get { return_getinstance (); } } Private StaticT _getinstance () {if(_instance = =NULL) {_instance= Findobjectoftype (typeof(T)) asT; if(_instance = =NULL) {Gameobject obj=NewGameobject (); //obj.hideflags = Hideflags.hideanddontsave;_instance = (T) obj. AddComponent (typeof(T)); Dontdestroyonload (obj); } } return_instance; } protected Virtual voidAwake () {Dontdestroyonload ( This. Gameobject); if(_instance = =NULL) {_instance= This asT; } Else{Destroy (gameobject); } } protected StaticT _instance;}
Unity Single-Case mode