单例模式是保证一个类只有一个对象被创建,并且不需要实例化,可以方便的使用.下面介绍几种unity的单例模式。
1 单例类(未继承Monobehaviour):
public class Singleton<T> where T : new()
{
private static T instance;
public static T Instance
{
get
{
if (instance == null)
{
instance = new T();
}
return instance;
}
}
}
2 单例(继承Monobehaviour)
继承了Monobehaviour的脚本不能直接通过new来实例化 只能通过拖动和findobjecttype的方法来实例化脚本。因此我们的单例写法也随之改变
public class Singleton2<T> : MonoBehaviour where T :MonoBehaviour
{
private static T instance;
public static T Instance
{
get
{
if (instance == null)
{
instance =FindObjectOfType<T>();
}
return instance;
}
}
}