Files
TuanTuan-Engine/Assets/GameFramework/Runtime/SingletonMono.cs

32 lines
986 B
C#
Raw Normal View History

2025-11-03 00:24:36 +08:00
using UnityEngine;
2025-11-12 07:04:31 +08:00
namespace Tuan.GameFramework
2025-11-03 00:24:36 +08:00
{
2025-11-12 07:04:31 +08:00
public class SingletonMono<T> : MonoBehaviour where T : MonoBehaviour
2025-11-03 00:24:36 +08:00
{
2025-11-12 07:04:31 +08:00
private static T _instance;
private static readonly object _lock = new object();
public static T Inst
2025-11-03 00:24:36 +08:00
{
2025-11-12 07:04:31 +08:00
get
2025-11-03 00:24:36 +08:00
{
2025-11-12 07:04:31 +08:00
lock (_lock)
2025-11-03 00:24:36 +08:00
{
if (_instance == null)
{
2025-11-12 07:04:31 +08:00
_instance = FindAnyObjectByType<T>();
if (_instance == null)
{
GameObject singletonObject = new GameObject(typeof(T).Name);
DontDestroyOnLoad(singletonObject);
_instance = singletonObject.AddComponent<T>();
Debug.Log($"实例化{singletonObject.name}");
}
2025-11-03 00:24:36 +08:00
}
2025-11-12 07:04:31 +08:00
return _instance;
2025-11-03 00:24:36 +08:00
}
}
}
}
}