單例模式通常用於項目的模塊管理,在Unity中主要用兩種單例,一種是基於C#普通單例,一種是繼承了Unity的MonoBehaviour的單例。
1.普通單例
where 限制模板的類型, new()指的是這個類型必須要能被實例化
加lock以保證我們的單例是線程安全的。
public abstract class Singleton<T> where T : new() {
private static T _instance;
private static object mutex = new object();
public static T instance {
get {
if (_instance == null) {
lock (mutex) {
if (_instance == null) {
_instance = new T();
}
}
}
return _instance;
}
}
}
2.繼承MonoBehaviour的單例
這類單例可以訪問Unity的組件,常用於聲音、動畫、UI管理模塊
因爲MonoBehaviour不支持多線程訪問,所以這裏不用加鎖
public class UnitySingleton<T> : MonoBehaviour
where T : Component {
private static T _instance = null;
public static T Instance {
get {
if (_instance == null) {
_instance = FindObjectOfType(typeof(T)) as T;
if (_instance == null) {
GameObject obj = new GameObject();
_instance = (T)obj.AddComponent(typeof(T));
obj.hideFlags = HideFlags.DontSave;
// obj.hideFlags = HideFlags.HideAndDontSave;
obj.name = typeof(T).Name;
}
}
return _instance;
}
}
public virtual void Awake() {
DontDestroyOnLoad(this.gameObject);
if (_instance == null) {
_instance = this as T;
}
else {
GameObject.Destroy(this.gameObject);
}
}
}