单例模式通常用于项目的模块管理,在Unity中主要用两种单例,一种是基于C#普通单例unity单例模式,一种是继承了Unity的MonoBehaviour的单例。
1.普通单例
where 限制模板的类型, new()指的是这个类型必须要能被实例化
加lock以保证我们的单例是线程安全的。
public abstract class Singleton 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的组件unity单例模式像素游戏素材游戏开发素材,常用于声音、动画、UI管理模块
因为MonoBehaviour不支持多线程访问,所以这里不用加锁
public class UnitySingleton : 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);
}
}
}
文章来源:https://blog.csdn.net/yasinxin/article/details/105893677