using UnityEngine;
|
|
|
public class SingletonMonobehaviour<T> : MonoBehaviour where T : MonoBehaviour
|
{
|
|
private static volatile T s_Instance = null;
|
private static object s_Root = new object();
|
|
public static T Instance
|
{
|
get
|
{
|
if (s_Instance == null)
|
{
|
lock (s_Root)
|
{
|
T[] _instances = (T[])FindObjectsOfType(typeof(T));
|
string _name = typeof(T).Name;
|
if (_instances != null)
|
{
|
for (var i = 0; i < _instances.Length; i++)
|
{
|
Destroy(_instances[i].gameObject);
|
//Debug.Log("销毁了: " + _name);
|
}
|
}
|
//Debug.Log("创建了: " + _name);
|
GameObject _go = new GameObject();
|
_go.name = _name;
|
s_Instance = _go.AddComponent<T>();
|
DontDestroyOnLoad(_go);
|
}
|
}
|
return s_Instance;
|
}
|
}
|
|
public static bool IsValid()
|
{
|
return s_Instance != null;
|
}
|
|
protected virtual void OnDestroy()
|
{
|
// Debug.Log("执行了销毁");
|
s_Instance = null;
|
}
|
}
|