Unity万能单利

万能单利 只要一个类继承这个万能单利类就行

using UnityEngine;
public class MonoSingleton : MonoBehaviour where T : MonoSingleton
{
private static T m_Instance = null;

public static T Indance
{
    get
    {
        if (m_Instance == null)
        {
            m_Instance = GameObject.FindObjectOfType(typeof(T)) as T;
            if (m_Instance == null)
            {
                m_Instance = new GameObject("Singleton of " + typeof(T).ToString(), typeof(T)).GetComponent<T>();
            }

        }
        return m_Instance;
    }
}
private void Awake()
{
    if (m_Instance == null)
    {
        m_Instance = this as T;
    }
}

private void OnApplicationQuit()
{
    m_Instance = null;
}
}

2、用法说明
创建一个脚本来继承 这个类
这里写图片描述

3、VideoManager这个脚本就是一个单利了 ,在别的脚本中就可以直接调用这个脚本中的方法和属性了
这里写图片描述

4、Monosingleton 这个脚本和 VideoManager 这个脚本可挂可不挂在游戏对象上,如果不挂运行的时候会生成相对应的游戏对象(身上挂载的有对应的脚本)
这里写图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43109909/article/details/82287738