繼承MonoBehaviour的單例類
阿新 • • 發佈:2018-11-28
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()函式執行的寫在此函式
}
}