Ensure that a class has only one instance and provides a function to access him.
The first is the simplest, but does not consider thread safety, which can be problematic in multi-threading.
public class singleton{ static Singleton _instance = ; private Singleton () {} public static Singleton CreateInstance () { if (_instance = = null = new Singleton (); return _instance; }}
The second takes into account the multi-threaded situation and increases the lock.
Public classsingleton{Private volatile StaticSingleton _instance =NULL; Private Static ReadOnly ObjectLockhelper =New Object(); PrivateSingleton () {} Public StaticSingleton CreateInstance () {if(_instance = =NULL) { Lock(lockhelper) {if(_instance = =NULL) _instance=NewSingleton (); } } return_instance; }}
Applying a single case to U3D development
Public Abstract classU3dsingleton<t>: MonobehaviourwhereT:u3dsingleton<t>{ Private StaticT m_instance =NULL; Private Static ReadOnly ObjectLockhelper =New Object(); Public StaticT instance{Get{ if(M_instance = =NULL ) { Lock(lockhelper) {m_instance= Findobjectoftype (typeof(T)) asT; if(M_instance = =NULL) {m_instance=NewGameobject ("Singleton of"+typeof(T). ToString (),typeof(T)). Getcomponent<t>(); } } } returnm_instance; } } Public voidInitsingle () {if(M_instance = =NULL) {m_instance= This asT; } }}
This class can only be used to allow the user to inherit it, but in Unity3d programming if the initialization is inactive object,
The Findobjectoftype function returns to NULL, and it is not possible to return the object of our script, so we need to call it ourselves in the awake function of the subclass.
The Initsingle function.
The use of inheritance is not conducive to extension, we can use the composition in the subclass of the way, as follows
Public class gametool:monobehaviour{ public gametool getinstance () { return U3dsingleton<gametool>. instance; } }
Singleton Mode C #