(client) feat:Add Singleton and MonoSingleton class
This commit is contained in:
3
Client/Assets/Scripts/Utils.meta
Normal file
3
Client/Assets/Scripts/Utils.meta
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
fileFormatVersion: 2
|
||||||
|
guid: 44fba140ed5941d3999e1ff66685b176
|
||||||
|
timeCreated: 1752049808
|
32
Client/Assets/Scripts/Utils/MonoSingleton.cs
Normal file
32
Client/Assets/Scripts/Utils/MonoSingleton.cs
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
using UnityEngine;
|
||||||
|
|
||||||
|
namespace Utils
|
||||||
|
{
|
||||||
|
public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoBehaviour
|
||||||
|
{
|
||||||
|
private static T _instance;
|
||||||
|
public bool isGlobal = true;
|
||||||
|
|
||||||
|
public static T Instance => _instance ??= FindFirstObjectByType<T>();
|
||||||
|
|
||||||
|
private void Awake()
|
||||||
|
{
|
||||||
|
Debug.LogWarning($"{typeof(T)} [{GetInstanceID()}] Awake");
|
||||||
|
if (isGlobal)
|
||||||
|
{
|
||||||
|
if (_instance is not null && _instance != gameObject.GetComponent<T>())
|
||||||
|
{
|
||||||
|
Destroy(gameObject);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
DontDestroyOnLoad(gameObject);
|
||||||
|
_instance = gameObject.GetComponent<T>();
|
||||||
|
}
|
||||||
|
|
||||||
|
OnStart();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected abstract void OnStart();
|
||||||
|
}
|
||||||
|
}
|
2
Client/Assets/Scripts/Utils/MonoSingleton.cs.meta
Normal file
2
Client/Assets/Scripts/Utils/MonoSingleton.cs.meta
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
fileFormatVersion: 2
|
||||||
|
guid: 9abe30aefbadea24b9a23da5020a413c
|
8
Client/Assets/Scripts/Utils/Singleton.cs
Normal file
8
Client/Assets/Scripts/Utils/Singleton.cs
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
namespace Utils
|
||||||
|
{
|
||||||
|
public class Singleton<T> where T : new()
|
||||||
|
{
|
||||||
|
private static T _instance;
|
||||||
|
public static T Instance => _instance ??= new T();
|
||||||
|
}
|
||||||
|
}
|
2
Client/Assets/Scripts/Utils/Singleton.cs.meta
Normal file
2
Client/Assets/Scripts/Utils/Singleton.cs.meta
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
fileFormatVersion: 2
|
||||||
|
guid: 0937f7a41cd612b4aae1f33f9c1d938a
|
Reference in New Issue
Block a user