继承MonoBehaviour的单例类

1、MonoSingleton 

using UnityEngine;

public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoBehaviour
{
    public bool global = true;
    static T instance;
    public static T Instance
    {
        get
        {
            if (instance == null)
            {
                instance = (T)FindObjectOfType<T>();
            }
            return instance;
        }

    }

    void Start()
    {
        if (global)
        {
            if (instance != null && instance != this.gameObject.GetComponent<T>())
            {
                Destroy(this.gameObject);
                return;
            }
            DontDestroyOnLoad(this.gameObject);
            instance = this.gameObject.GetComponent<T>();
        }
        this.OnStart();
    }

    protected virtual void OnStart()
    {

    }
}

2、继承单例类

using UnityEngine;

public class Test : MonoSingleton<Test>
{
    protected override void OnStart()
    {
        //不能写 void Start(),会重写抽象类的Start
        //想要在Start()函数执行的写在此函数
    }
}

猜你喜欢

转载自blog.csdn.net/SimulationPD/article/details/84581038
今日推荐