1
0
mirror of https://github.com/oliverbooth/X10D synced 2024-11-13 02:15:42 +00:00
X10D/X10D.Unity/src/Singleton.cs
Oliver Booth 7e7825a170
fix: suppress CA1000
This analyzer warning does not apply here.
2023-04-02 03:10:58 +01:00

61 lines
1.6 KiB
C#

using UnityEngine;
namespace X10D.Unity;
/// <summary>
/// Represents a class which implements the singleton pattern for a specific <see cref="MonoBehaviour" />. This class is not
/// thread-safe.
/// </summary>
/// <typeparam name="T">The type of the singleton.</typeparam>
public abstract class Singleton<T> : MonoBehaviour
where T : Singleton<T>
{
private static Lazy<T> s_instanceLazy = new(CreateLazyInstanceInternal, false);
private static T? s_instance;
/// <summary>
/// Gets the instance of the singleton.
/// </summary>
/// <value>The singleton instance.</value>
#pragma warning disable CA1000
public static T Instance
#pragma warning restore CA1000
{
get => s_instance ? s_instance! : s_instanceLazy.Value;
}
/// <summary>
/// Called when the script instance is being loaded.
/// </summary>
protected virtual void Awake()
{
s_instance = (T?)this;
}
/// <summary>
/// Called when the object is destroyed.
/// </summary>
protected virtual void OnDestroy()
{
s_instance = null;
s_instanceLazy = new Lazy<T>(CreateLazyInstanceInternal, false);
}
private static T CreateLazyInstanceInternal()
{
if (s_instance)
{
return s_instance!;
}
if (FindObjectOfType<T>() is { } instance)
{
s_instance = instance;
return instance;
}
var gameObject = new GameObject {name = typeof(T).Name};
return s_instance = gameObject.AddComponent<T>();
}
}