using UnityEngine;
namespace X10D.Unity;
///
/// Represents a class which implements the singleton pattern for a specific . This class is not
/// thread-safe.
///
/// The type of the singleton.
[Obsolete("This implementation of the singleton pattern is discouraged, and this class will be removed in future. " +
"DO NOT USE THIS TYPE IN PRODUCTION.")]
public abstract class Singleton : MonoBehaviour
where T : Singleton
{
private static Lazy s_instanceLazy = new(CreateLazyInstanceInternal, false);
///
/// Gets the instance of the singleton.
///
/// The singleton instance.
public static T Instance
{
get => s_instanceLazy.Value;
}
///
/// Called when the object is destroyed.
///
protected virtual void OnDestroy()
{
s_instanceLazy = new Lazy(CreateLazyInstanceInternal, false);
}
private static T CreateLazyInstanceInternal()
{
if (FindObjectOfType() is { } instance)
{
return instance;
}
var gameObject = new GameObject {name = typeof(T).Name};
return gameObject.AddComponent();
}
}