Unity中实现单例,以及MonoBehaviour的单例工具类

148 阅读1分钟

我们在Unity开发中常常用到单例,以下是我封装的单例,方便后续使用,哈哈

using System;
using UnityEngine;

namespace UTools
{
    public abstract class Singleton<T> where T : new()
    {
        private static T _singleton;
        private static object mutex = new object();

        public static T instance
        {
            get
            {
                if (_singleton == null)
                {
                    lock (mutex) //保证单例线程是安全的
                    {
                        if (_singleton == null)
                        {
                            _singleton = new T();
                        }
                    }
                }

                return _singleton;
            }
        }
    }

    public  class UnitySingleton<T> : MonoBehaviour
        where T : Component
    {
        private static T _instance;

        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.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);
            }
        }
    }
}