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()函数执行的写在此函数
}
}