创建单例基类的方式

方式一:(不继承于MonoBehavior的单例)

/// <summary>
/// 不继承任何类的单例基类
/// </summary>
public abstract class BaseIns<T> where T : class, new()
{
    private readonly static object locaObj = new object();
    private static T instance = null;
    public static T Instance
    {
        get
        {
            if (instance == null)
            {
                lock (locaObj)
                {
                    if (instance == null)
                    {
                        instance = new T();
                    }
                }
            }
            return instance;
        }
    }
}

 

方式二:(继承于MonoBehavior的单例基类)

using UnityEngine;

/// <summary>
/// 继承MonoBehavior的单例基类
/// </summary>
/// <typeparam name="T"></typeparam>
public class BaseAutoMono<T> : MonoBehaviour where T:MonoBehaviour
{
    private static T instance;

    public static T Instance()
    {
        if (instance==null )
        {
            GameObject go = new GameObject();
            go.name = typeof(T).ToString();
            DontDestroyOnLoad(go);
            instance = go.AddComponent<T>();
        }
        return instance;
    }
}

 

以上内容仅作为个人记录,如有不对欢迎指正!

posted @ 2020-12-10 17:03  一世癫狂  阅读(133)  评论(0)    收藏  举报