In the game, some gameobjects (such as network managers) are required to exist throughout the game's lifecycle and exist in the form of a singleton.
In xgame, the singleton method is that the singleton script inherits from the monosingle class, And the monosingleton implementation method is called in awake ().
Dontdestroyonload(Gameobject); To ensure the Singleton. Implementation Code of the monosingleton class:
1 /// <summary> 2 /// Generic Mono singleton. 3 /// </summary> 4 using UnityEngine; 5 6 public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>{ 7 8 private static T mInstance = null; 9 10 public static T Instance{11 get{12 return mInstance;13 }14 }15 16 private void Awake(){17 18 if (mInstance == null)19 {20 DontDestroyOnLoad(gameObject);21 mInstance = this as T;22 mInstance.Init();23 }24 else25 {26 Destroy(gameObject);27 }28 }29 30 public virtual void Init(){}31 32 public virtual void Fini(){}33 34 35 private void OnApplicationQuit(){36 mInstance.Fini();37 mInstance = null;38 }39 }
The script that requires Singleton control only needs to inherit from the monosigleton class. Rewrite the init method to initialize the singleton class and rewrite Fini to clean up the job. For example:
[Unity] Single Instance in Game