Unity_C#_单例模式

C#_单例模式

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

//继承自Monobehaviour类单例
public class SingletonMono<T> : MonoBehaviour where T : MonoBehaviour
{
    private static object m_Lock = new object();

    private static T m_Instance;
    public static T Instance
    {
        get
        {
            if (m_Instance == null)
            {
                //避免多线程时同时调用
                lock (m_Lock)
                {
                    if (m_Instance == null)
                    {
                        m_Instance = GameObject.FindObjectOfType<T>();
                        if(m_Instance == null)
                        {
                            GameObject go = new GameObject();
                            m_Instance = go.AddComponent<T>();
                            go.name = typeof(T).ToString();
                            DontDestroyOnLoad(go);
                        }
                    }
                }
            }
            return m_Instance;
        }
    }
}


//纯类单例
public class Singleton<T> where T : class, new()
{
    private static object m_Lock = new object();

    private static T m_Instance;
    public static T Instance
    {
        get
        {
            if (m_Instance == null)
            {
                //避免多线程时同时调用
                lock (m_Lock)
                {
                    if (m_Instance == null)
                    {
                        m_Instance = new T();
                    }
                }
            }
            return m_Instance;
        }
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐