feat: initial commit
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace JoeSiu.Common.Infrastructure.Runtime
|
||||
{
|
||||
/// <summary>
|
||||
/// <see href="https://youtu.be/6kWUGEQiMUI"/>
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public abstract class ScriptableObjectSingleton<T> : ScriptableObject where T : ScriptableObjectSingleton<T>
|
||||
{
|
||||
private static T _instance;
|
||||
public static T Instance
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_instance != null) return _instance;
|
||||
|
||||
var assets = Resources.LoadAll<T>("");
|
||||
|
||||
if (assets.Length > 0)
|
||||
{
|
||||
AssignInstance(assets[0]);
|
||||
}
|
||||
|
||||
if (assets.Length > 1)
|
||||
{
|
||||
Debug.LogError(
|
||||
$"[ScriptableObjectSingleton] More than 1 instance of Singleton Scriptable Object of type: {typeof(T)} found");
|
||||
}
|
||||
|
||||
if (!_instance)
|
||||
{
|
||||
Debug.LogWarning(
|
||||
$"[ScriptableObjectSingleton] No instance of type '{typeof(T).Name}' is found, make sure to add it to the Resources folder!");
|
||||
}
|
||||
|
||||
return _instance;
|
||||
}
|
||||
}
|
||||
|
||||
public static T GetInstance() => _instance;
|
||||
|
||||
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
|
||||
public static void RemoveInstance()
|
||||
{
|
||||
_instance = null;
|
||||
Debug.Log($"[ScriptableObjectSingleton] Removed instance of type '{typeof(T).Name}'");
|
||||
}
|
||||
|
||||
private static void AssignInstance(T instance)
|
||||
{
|
||||
if (!instance) return;
|
||||
_instance = instance;
|
||||
Debug.Log($"[ScriptableObjectSingleton] Assigned instance of type '{typeof(T).Name}' to object '{instance.name}'", instance);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user