U3D中许多地方需要用到单例,然后就是如下的情况:
private static SoundManager _instance;
public static SoundManager GetInstance
{
return _instance;
}
void Awake()
{
_instance = this;
}
假如以上的代码没有任何问题,但是每个单例都要加上这么一段代码也是挺烦的,所有可以加上泛型。
using UnityEngine;
public abstract class Singleton<T> :MonoBehaviour
where T:MonoBehaviour
{
private static T _instance = null;
public static T Instance
{
get { return _instance; }
}
protected virtual void Awake()
{
_instance = this as T;
}
}
当然更好的是下面这一种。
using UnityEngine;
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T _instance;
private static object _lock = new object();
private static bool applicationIsQuitting = false;
public static T GetInstance
{
get
{
if (applicationIsQuitting)
{
return null;
}
lock (_lock) // 可以确保代码完整运行 不会被线程打断
{
if (null == _instance)
{
_instance = (T) FindObjectOfType(typeof (T));
if (FindObjectOfType(typeof (T)).Length > 1)
{
return _instance;
}
if (null == _instance)
{
GameObject singleton = new GameObject();
_instance = singleton.AddComponent<T>();
singleton.name = "(singleton)" + typeof (T).ToString();
DontDestroyOnLoad(singleton);
}
}
return _instance;
}
}
}
public void OnDestroy()
{
applicationIsQuitting = true;
}
}