1. 程式人生 > >繼承MonoBehaviour的單例類

繼承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()函式執行的寫在此函式
    }
}