2022-05-13 08:54:00 +01:00
|
|
|
|
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>
|
2022-05-31 11:52:59 +01:00
|
|
|
|
[Obsolete("This implementation of the singleton pattern is discouraged, and this class will be removed in future. " +
|
|
|
|
|
"DO NOT USE THIS TYPE IN PRODUCTION.")]
|
2022-05-13 08:54:00 +01:00
|
|
|
|
public abstract class Singleton<T> : MonoBehaviour
|
|
|
|
|
where T : Singleton<T>
|
|
|
|
|
{
|
|
|
|
|
private static Lazy<T> s_instanceLazy = new(CreateLazyInstanceInternal, false);
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Gets the instance of the singleton.
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <value>The singleton instance.</value>
|
|
|
|
|
public static T Instance
|
|
|
|
|
{
|
|
|
|
|
get => s_instanceLazy.Value;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Called when the object is destroyed.
|
|
|
|
|
/// </summary>
|
|
|
|
|
protected virtual void OnDestroy()
|
|
|
|
|
{
|
|
|
|
|
s_instanceLazy = new Lazy<T>(CreateLazyInstanceInternal, false);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private static T CreateLazyInstanceInternal()
|
|
|
|
|
{
|
|
|
|
|
if (FindObjectOfType<T>() is { } instance)
|
|
|
|
|
{
|
|
|
|
|
return instance;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var gameObject = new GameObject {name = typeof(T).Name};
|
|
|
|
|
return gameObject.AddComponent<T>();
|
|
|
|
|
}
|
|
|
|
|
}
|