Unity的单例

单例模式通常用于项目的模块管理,在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);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/YasinXin/article/details/105893677
今日推荐