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()函数执行的写在此函数
}
}
本文深入探讨了Unity中实现单例模式的一种方法:MonoSingleton。通过抽象类MonoSingleton<T>,确保了场景中仅存在一个实例,并在场景切换时不被销毁。具体展示了如何继承该单例类并正确重写OnStart方法。
4762

被折叠的 条评论
为什么被折叠?



