1. Inherited from MonoBehaviour (not destroyed with scene switching)
Base class code:
1 using System.Collections; 2 using System.Collections.Generic; 3 using UnityEngine; 4 5 /// <summary> 6 /// Singleton mode base class, inherited from MonoBehaviour, not destroyed with scene switching 7 /// In Create a new empty object DDOL in the scene, mount T class to inherit DDOLSingleton < T> 8 /// </summary> 9 /// <typeparam name="T"></typeparam> 10 public abstract class DDOLSingleton<T> : MonoBehaviour where T : DDOLSingleton<T> 11 { 12 protected static T _instance = null; 13 14 public static T Instance 15 { 16 get 17 { 18 if (null == _instance) 19 { 20 GameObject go = GameObject.Find("DDOL"); 21 if (null == go) 22 { 23 go = new GameObject("DDOL"); 24 DontDestroyOnLoad(go); 25 } 26 _instance = go.GetComponent<T>(); 27 if (null == _instance) 28 { 29 _instance = go.AddComponent<T>(); 30 } 31 } 32 return _instance; 33 } 34 } 35 }
test:
Create a new empty entity DDOL and mount the script GameManage.
Create a new button to implement the function of loading the next scene, and test whether it will be destroyed when the scene is destroyed.
Hierarchy :
GameManage code:
1 using System.Collections.Generic; 2 using UnityEngine; 3 4 /// <summary> 5 /// 单例 6 /// </summary> 7 public class GameManage : DDOLSingleton<GameManage> { 8 public void TestMethod() 9 { 10 Debug.Log("GameManage"); 11 } 12 }
Test code:
1 /// <summary> 2 /// 测试单例 3 /// </summary> 4 public class Test : MonoBehaviour { 5 6 // Use this for initialization 7 void Start () { 8 GameManage.Instance.TestMethod(); 9 } 10 11 // Update is called once per frame 12 void Update () { 13 14 } 15 16 public void OnBtnClick() 17 { 18 SceneManager.LoadScene(1); 19 } 20 }
Effect picture:
2. Not inherited from MonoBehaviour (destroyed with scene switching)
Base class code:
1 /// <summary> 2 /// Base class of singleton mode, not inherited from MonoBehaviour, and destroyed with scene switching 3 /// Mount T class to inherit DDOLSingleton <T> , just overload the Init function 4 // / </summary> 5 /// <typeparam name="T"></typeparam> 6 public abstract class Singleton<T> where T : class , new () 7 { 8 protected static T _instance = null ; 9 10 public static T Instance 11 { 12 get 13 { 14 if (null == _instance) 15 { 16 _instance = new T(); 17 } 18 return _instance; 19 } 20 } 21 22 protected Singleton() 23 { 24 if (null != _instance) 25 { 26 Debug.LogError("This " + typeof(T).ToString() + " Singleton Instance is not null !!!"); 27 } 28 Init(); 29 } 30 31 public virtual void Init() 32 { 33 34 } 35 }
At this point, the GameManage code is modified to:
1 /// <summary> 2 /// 测试 Singleton 3 /// </summary> 4 public class GameManage : Singleton<GameManage> { 5 public override void Init() 6 { 7 base.Init(); 8 } 9 10 public void TestMethod() 11 { 12 Debug.Log("GameManage"); 13 } 14 }