最近在看一些框架类型的教学,发现有很多的基类Manager都是要做成单例模式的,而每次实现单例都要在每个Manager里面重新写一段代码,因此我尝试着自己写了一个基类,所有继承这个类的派生类都是单例的。直接上代码:
using UnityEngine;
[DisallowMultipleComponent]
public abstract class Singlton<T> : MonoBehaviour where T : MonoBehaviour
{
protected static T _instance;
public static T Instance
{
protected set
{
_instance = value;
}
get
{
if(_instance == null)
{
_instance = FindObjectOfType<T>();
if(_instance == null)
{
GameObject go = new GameObject(typeof(T).Name);
Instance = go.AddComponent<T>();
DontDestroyOnLoad(go);
}
}
return _instance;
}
}
这样每次使用的话继承一下这个基类就可以了,代码如下:
public class Test : Singlton<Test>