53 lines
1.4 KiB
C#
53 lines
1.4 KiB
C#
using UnityEngine;
|
|
|
|
public class MBSingletonManager<T> : MonoBehaviour where T : MonoBehaviour
|
|
{
|
|
/// <summary>
|
|
/// 存储唯一实例的私有静态变量
|
|
/// </summary>
|
|
private static T instance;
|
|
|
|
/// <summary>
|
|
/// 用于锁定的对象
|
|
/// </summary>
|
|
private static readonly object mlock = new object();
|
|
|
|
/// <summary>
|
|
/// 公共静态属性用于访问实例
|
|
/// </summary>
|
|
public static T Instance
|
|
{
|
|
get
|
|
{
|
|
// 使用锁确保线程安全
|
|
lock (mlock)
|
|
{
|
|
if (instance == null)//如果实例为空,则寻找现有的实例
|
|
{
|
|
instance = FindObjectOfType<T>();
|
|
|
|
if (instance == null)//如果场景中没有找到实例,则创建一个新的
|
|
{
|
|
GameObject singletonObject = new GameObject(typeof(T).Name);
|
|
instance = singletonObject.AddComponent<T>();
|
|
}
|
|
DontDestroyOnLoad(instance); //保持单例在场景切换时不被销毁
|
|
}
|
|
return instance;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 释放单例
|
|
/// </summary>
|
|
public virtual void ReleaseInstance()
|
|
{
|
|
if (instance != null)
|
|
{
|
|
Destroy(instance.gameObject);
|
|
instance = null; // 释放引用
|
|
}
|
|
}
|
|
}
|