Unity Singleton Singleton Class (Unity3d development 20)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.