(client) feat:Add Singleton and MonoSingleton class
This commit is contained in:
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();
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user