单例模板类:以下代码解决了每个单例类都需要重复写同样代码的问题,基本上算一个比较好的解决方案。
public sealed class SingletonTemplate : MonoBehaviour where T : MonoBehaviour
{
private static volatile T instance;
private static object syncRoot = new Object();
public static T Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
{
T[] instances = FindObjectsOfType();
if (instances != null)
{
for (var i = 0; i < instances.Length; i++)
{
Destroy(instances[i].gameObject);
}
}
GameObject go = new GameObject();
go.name = typeof(T).Name;
instance = go.AddComponent();
DontDestroyOnLoad(go);
}
}
}
return instance;
}
}
}