在unity中,经常需要使用到单例,尤其是MonoBehaviour的单例。
MonoBehaviour的单例模式需要使用饿汉模式的单例来初始化,要不然可能会自动创建多出的单例。
MonoBehaviour单例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| using UnityEngine;
public class MonoSingleton<T> : MonoBehaviour where T : Component { private static T _instance = null;
public static T Instance { get { if (_instance == null) { _instance = FindObjectOfType<T>(); if (_instance == null) { GameObject obj = new GameObject(typeof(T).Name, new[] {typeof(T)}); DontDestroyOnLoad(obj); _instance = obj.GetComponent<T>(); (_instance as IInitable)?.Init(); } else { Debug.LogWarning("Instance is already exist!"); } }
return _instance; } }
protected void Awake() { _instance = this as T; DontDestroyOnLoad(this.transform.root); } }
|
非MonoBehaviour单例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
public class Singleton<T> where T : new() { private static T _instance;
public static T Instance { get { if (_instance == null) { _instance = new T(); (_instance as IInitable)?.Init(); }
return _instance; } } }
|