首次提交
This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
namespace Roy
|
||||
{
|
||||
/// <summary>
|
||||
/// 管理类基类
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public class BaseManager<T> where T : new()
|
||||
{
|
||||
private static T _instance;
|
||||
|
||||
public static T GetInstance
|
||||
{
|
||||
get
|
||||
{
|
||||
_instance ??= new T();
|
||||
return _instance;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 91c3234e0b0b4940992129af43d62f99
|
||||
timeCreated: 1727164456
|
||||
@@ -0,0 +1,55 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace Roy
|
||||
{
|
||||
|
||||
public class SingletonMonoBehaviour<T> : MonoBehaviour where T : MonoBehaviour
|
||||
{
|
||||
private static T _instance;
|
||||
|
||||
public static T Instance
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_instance == null)
|
||||
{
|
||||
// 尝试找到已存在的实例
|
||||
_instance = FindObjectOfType<T>();
|
||||
|
||||
// 如果没有找到,则创建一个新的实例
|
||||
if (_instance == null)
|
||||
{
|
||||
GameObject singletonObject = new GameObject(typeof(T).Name);
|
||||
_instance = singletonObject.AddComponent<T>();
|
||||
DontDestroyOnLoad(singletonObject); // 不在场景切换时销毁
|
||||
}
|
||||
}
|
||||
|
||||
return _instance;
|
||||
}
|
||||
}
|
||||
|
||||
// 确保在场景中只存在一个实例
|
||||
protected virtual void Awake()
|
||||
{
|
||||
if (_instance == null)
|
||||
{
|
||||
_instance = this as T;
|
||||
}
|
||||
else if (_instance != this)
|
||||
{
|
||||
Debug.LogWarning($"An instance of {typeof(T)} already exists! Destroying this instance.");
|
||||
Destroy(gameObject); // 如果有其他实例,销毁当前对象
|
||||
}
|
||||
}
|
||||
|
||||
protected virtual void OnDestroy()
|
||||
{
|
||||
if (_instance == this)
|
||||
{
|
||||
_instance = null; // 清除引用
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 54bf3c952fe4494dbae47a7a63806362
|
||||
timeCreated: 1728986962
|
||||
Reference in New Issue
Block a user