单例模式基类模块的主要作用是减少单例模式重复代码的书写。
1. 单例模式基类
public class Singleton<T> where T : new()
{
private static T _instance = new T();
public static T Instance {
get {
return _instance;
}
}
}
2. 继承MonoBehaviour的单例模式基类
public class MonoSingleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T _instance;
public static T Instance {
get {
if (_instance == null) {
GameObject obj = new GameObject();
obj.name = typeof(T).Name;
DontDestroyOnLoad(obj);
_instance = obj.AddComponent<T>();
}
return _instance;
}
}
}