First, add a single example template class
usingUnityengine; Public classSingleton<t>: Monobehaviourwheret:monobehaviour{Private StaticT _instance; Private Static Object_lock =New Object (); Public StaticT Instance {Get { if(applicationisquitting) {return NULL; } Lock(_lock) {if(_instance = =NULL) {_instance= (T) findobjectoftype (typeof(T)); if(Findobjectsoftype (typeof(T)). Length >1) { return_instance; } if(_instance = =NULL) {Gameobject singleton=NewGameobject (); _instance= Singleton. Addcomponent<t> (); Singleton.name="(Singleton)"+typeof(T). ToString (); Dontdestroyonload (singleton); } } return_instance; } } } Private Static BOOLApplicationisquitting =false; Public voidOnDestroy () {applicationisquitting=true; }}
Second, define their own singleton class
using Unityengine; using System; Public class Gamemanager:singleton<gamemanager> { publicfloat score; void Awake () { this. Init (); } Private void init () { // init code }}
Third, call the use
Gamemanager. Instance. score = ;
Original address: http://blog.csdn.net/cocos2der/article/details/47335197
Unity C # Single-instance mode implementation