上海虹口龙之梦项目
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

67 lines
1.6 KiB

using System;
using UnityEngine;
public class Singleton<T> : BaseBehaviour
where T : BaseBehaviour
{
private static bool m_ShuttingDown = false;
private static object m_Lock = new object();
private static T m_Instance;
// 单例对象在切换场景时不销毁
public virtual void Awake()
{
DontDestroyOnLoad(gameObject);
}
/// <summary>
/// 单例
/// </summary>
public static T Instance
{
get
{
if (m_ShuttingDown)
{
Debug.LogWarning($"[{typeof(T)}]已经销毁");
return null;
}
lock (m_Lock)
{
if (m_Instance == null)
{
// 找到单例对象
m_Instance = (T)FindObjectOfType(typeof(T));
// 对象为空创建新对象
if (m_Instance == null)
{
// 创建一个空对象
var singletonObject = new GameObject();
m_Instance = singletonObject.AddComponent<T>();
singletonObject.name = $"[{typeof(T).ToString()}]";
// Make instance persistent.
//DontDestroyOnLoad(singletonObject);
}
}
return m_Instance;
}
}
}
public virtual void Initialize() { }
private void OnApplicationQuit()
{
m_ShuttingDown = true;
}
private void OnDestroy()
{
m_ShuttingDown = true;
}
}