Unity Single-Case mode

Source: Internet
Author: User

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

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.