**
Unity中的设计模式之单例
**
首先静态和单例的区别,游戏开始了,静态就会一直在内存里,你的游戏不结束,他也不结束,如果你内存吃紧,而他又很大的时候,那他就很恶心了。但单例不一样,你不用他就不出现,你需要他就出来了,当你不想用他了你还可以把他销毁。
但是单例存在最大的问题就是初始化,在何时初始化。
- 继承MonoBehaviour的单例
public class SingleBase<T> : MonoBehaviour where T : SingleBase<T>
{
public static T Instance { get; private set; }
protected void Awake()
{
if (Instance == null)
{
Instance = (T) this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
}
- 不继承MonoBehaviour的单例
public class SingleBase<T> where T:new()
{
private static T instance;
public static T Instance
{
get
{
if (instance == null)
instance = new T();
return instance;
}
}
}