单例模式在开发中十分常用,反复的编写十分浪费时间。我们可以写一个基类,让单例的类继承自该基类即可,一劳永逸。
单例基类-普通C#类
public class Singleton<T> where T : new()
{
private static T instance;
public static T Instance
{
get
{
if (instance == null)
instance = new T();
return instance;
}
}
protected Singleton() { }
}
单例基类-继承自MonoBehavior
using UnityEngine;
public class MonoSingleton<T>: MonoBehaviour where T : MonoSingleton<T>
{
private static T instance;
public static T Instance
{
get
{
if(instance == null)
{
instance = FindObjectOfType<T>();
}
if(instance == null)
{
GameObject go = new GameObject();
instance = go.AddComponent<T>();
go.name = typeof(T).Name;
}
return instance;
}
}
}