Single case is the game development of the more common design patterns, although the function is different, but some features are common, code is also a lot, if you can put in a base class inside is best, but the singleton need to have a instance function to return the current object, so this function must be static, There is no way to directly inherit, the previous read "Object-oriented game development" This book, using generics, so I experimented with several times
Now we're going to implement this simpler single-case generics:
Public classSingleton<t>: MonobehaviourwhereT:monobehaviour//Because objects inheriting Monobehaviour cannot use new () to construct an instance, so this is only possible with monobehaviour{Private StaticT instance;//Instance target objectprotected Virtual voidAwake () { This. Checkinstance (); Awakening Check}protected BOOLcheckinstance ()//is unique, not to destroy redundant targets, to prevent the target from having multiple mounts on other gameobject. { if( This= = Singleton<t>. Instance) {return true; } UnityEngine.Object.Destroy ( This); return false; } Public StaticT Instance {Get { if(Singleton<t>.instance = =NULL) {Singleton<t>.instance = (T) UnityEngine.Object.FindObjectOfType (typeof(T));//NULL if the object is not instantiatedif(Singleton<t>.instance = =NULL) {Debug.logerror (typeof(T) +"Was no attached gameobject"); } } returnSingleton<t>. instance; } }}
The base class is done, and the following is a single example of the various functions derived:
Public class playerctrl:singleton<playerctrl>{ ...} .............................. ...} Public class gamemanager:singleton<gamemanager>{ ...} .............................. ...}
Notice that the base class is generic, so each singleton<t> is a different instance when used directly singleton<Playerctrl. Instance can return the Playerctrl of a single case.
Study of design Patterns in Unity3d <;: Generic single case