Monkey original, welcome reprint. Reproduced please specify: Reproduced from COCOS2DER-CSDN, thank you!
Original address: http://blog.csdn.net/cocos2der/article/details/47335197
Today I see a group of friends ask Unity single example of the best way to achieve, below I I often use. Put it up for everyone's reference.
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 void OnDestroy() {applicationisquitting =true; }}
This is a singleton template class, which is very simple to use.
Second, define their own singleton class
using UnityEngine;using System;publicclass GameManager : Singleton<GameManager> { publicfloat score; void Awake () { this.Init(); } privatevoidInit() { // Init code }}
Third, call the use
GameManager.Instance.score99;
If there is a better way to implement, you can recommend the next OH.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Unity Singleton Singleton Class (Unity3d development 20)