Unity3d and design mode (ii) Single case mode

Source: Internet
Author: User
Tags instance method

Why use Singleton mode

In our entire game life cycle, there are many objects from beginning to end with only one. This only instance needs to be generated once and will not be destroyed until the end of the game.
The singleton pattern is generally applied to the manager class, or to some object that needs to persist.

Implementation of single-case mode in Unity3d (i) the method of implementing Singleton pattern in C #

Because the single example itself is not the focus, so here is skipped, directly on the code.
The following code comes from MSDN.

 Public Sealed classSingleton {Private Static volatileSingleton instance;Private Static ObjectSyncRoot =NewObject ();Private Singleton() {} Public StaticSingleton Instance {Get{if(Instance = =NULL)           {Lock(SyncRoot) {if(Instance = =NULL) Instance =NewSingleton (); }          }returnInstance }    } }

The above code is a comparison of the full version of the C # single case. In unity, if you don't need to use monobeheviour, you can use this method to build a singleton.

(b) If it is a monobeheviour?

There are several important differences between Monobeheviour and general classes, which are reflected in the singleton pattern with two points.
First, Monohehaviour cannot be instantiated using constructors and can only be mounted on gameobject.
Second, when switching scenes, the Gameobject in the current scene will be destroyed (except when loadlevel with the additional parameter), in which case our singleton objects will be destroyed.
In order to keep it from being destroyed, we need to do dontdestroyonload processing. At the same time, in order to maintain only one instance of the scene, we want to judge the Singleton in the current scene, and if there are other instances, we should delete them all.
Therefore, the way to build a singleton becomes this.

 Public Sealed classsingletonmonobehaviour:monobehaviour{Private Static volatileSingletonmonobehaviour instance;Private Static ObjectSyncRoot =NewObject (); Public StaticSingletonmonobehaviour Instance {Get{if(Instance = =NULL)              {Lock(SyncRoot) {if(Instance = =NULL) {singletonmonobehaviour[] instances = (singletonmonobehaviour[]) Findobjectsoftype (typeof(Singletonmonobehaviour));if(Instances! =NULL){ for(vari =0; I < instances. Length;                            i++) {Destroy (instances[i].gameobject); }} gameobject go =NewGameobject ("__singletonmonobehaviour"); Instance = go.                        Addcomponent<singletonmonobehaviour> ();                     Dontdestroyonload (GO); }                }             }returnInstance }     } }

This approach is not perfect. The defects are at least:
* If there are many singleton classes, you will need to copy and paste the code
* There are times when we might want to use all the instances that are currently present instead of deleting all new instances. (This is not necessarily a defect, just a different design)
The code for this singleton pattern and the test will be attached later in this article.

(iii) Implementation of a single case using a template class

To avoid repeating the code, we can use the template class to generate the singleton. Non-monobehaviour implementation of the way here will not repeat, only say monobehaviour.
Code

 Public Sealed classSingletontemplate<t>: MonobehaviourwhereT:monobehaviour {Private Static volatileT instance;Private Static ObjectSyncRoot =NewObject (); Public StaticT Instance {Get{if(Instance = =NULL)              {Lock(SyncRoot) {if(Instance = =NULL) {t[] instances = (t[]) Findobjectsoftype (typeof(T));if(Instances! =NULL){ for(vari =0; I < instances. Length;                            i++) {Destroy (instances[i].gameobject); }} gameobject go =NewGameobject (); Go.name =typeof(T).                        Name; Instance = go.                        Addcomponent<t> ();                     Dontdestroyonload (GO); }                }             }returnInstance }     } }

The above code solves the problem that every singleton class needs to write the same code repeatedly, which is basically a better solution.

Some pits in a single case
    • The biggest pits are single-instance monobehaviour, whose lifecycles are not controlled by our programmers. The destroy of Monobehaviour itself will determine when an instance of a singleton class is destroyed. Therefore, be sure not to call the Singleton object in the OnDestroy function, which may cause the object to persist after the game is over (the original singleton has been destroyed, you create a new one, and of course it will not be destroyed again). For example, the following code is important to note.
void Start(){    Singleton.Instance.OnSomeTime += DoSth;}void OnDestroy(){    Singleton.Instance.OnSomeTime -= DoSth;}
    • In addition, it is not recommended to place Gameobject with a singleton class component in a scene or preset. Many online projects have this kind of notation. But my point is that it's not flexible enough. If you use this method, be aware that when you get instance, the first object you find is assigned to instance
ifnull)  {                        T[] instances = (T[])FindObjectsOfType(typeof(T));                        ifnull){                        instance = instances[0];                            for (var1; i < instances.Length; i++) {                                Destroy(instances[i].gameObject);                            }                        }    }
The difference between a single case and a static one

As we all know, static members or methods are only one part of the entire runtime. So there has been a dispute between static and Singleton mode.
In fact, both of these methods have their scope of application, not one-sided to say that some good or some kind of bad. The concrete argument is too much, the information is also many, here also not in-depth, simply explain the use of the difference between the two.
* The single-instance method can be inherited, not static.
* There is a single instance of the process of creating instances, the life cycle is not the entire runtime, static methods exist at compile time, the whole process is always valid.
Although the difference is actually very much, but here only one of the most central question, how to choose?

It's actually very simple, from an object-oriented point of view--
* If the state of the instance itself needs to be used in the method, that is, when the member of the instance needs to be used, this method must be an instance method, use a singleton call.
* This method must be a static method if the method does not involve the instance at all, but rather the state of the class share, or even if it does not require any state.
From the point of view of application, I think the above is enough, as for the difference in memory consumption Ah, GC and efficiency differences AH these I think more is the theory, not close to the actual use.

A single case is good, do not misuse

Abuse of design patterns is a problem that many people will encounter, especially for beginners. Design patterns should be used only in the right scenario, rather than using a single instance everywhere.
In fact, the abuse of a single case can lead to some of the following problems:
* The coupling of the code may be increased. Calling MusicController.instance.Play in a module may prevent the module from being reused independently.
* The responsibilities of a single class may be too large to violate the principle of single responsibility.
* Some performance problems can occur in some cases.
You can use some other method instead of the singleton mode, where it is not extended for the time being.

Single case without a single case

In some cases I will use this method to build a unique instance.
Game.Instance.MusicController or Game.musiccontroller.
As a single member of a higher-level controller or a class variable, the same instance can have only one copy of the entire game.
The advantage is that extensibility is better because we can add Game.Instance.ReleaseMusicController at any time, and so on. This is no longer extended.
The code for this article is as follows
Singleton

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Unity3d and design mode (ii) 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.