Files
Ultimate-Fishing-Simulator-…/Assets/Scripts/Assembly-CSharp/UFS3/Management/Singleton.cs
2026-03-04 09:37:33 +08:00

50 lines
945 B
C#

using UnityEngine;
namespace UFS3.Management
{
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T _instance;
private static readonly object _lock = new object();
public static T Instance
{
get
{
if (_instance == null)
{
lock (_lock)
{
if (_instance == null)
{
_instance = Object.FindObjectOfType<T>();
if (_instance == null)
{
GameObject obj = new GameObject(typeof(T).Name);
_instance = obj.AddComponent<T>();
Object.DontDestroyOnLoad(obj);
}
}
}
}
return _instance;
}
}
protected virtual void Awake()
{
if (_instance != null && _instance != this)
{
Debug.Log("Copy of Singleton Instance already exists, destroying new one.");
Object.Destroy(base.gameObject);
}
else
{
_instance = this as T;
Object.DontDestroyOnLoad(base.gameObject);
}
}
}
}