using System;
using UnityEngine;
namespace Unity.XR.XREAL
{
///
/// A generic singleton MonoBehaviour base class that ensures only one instance of the type exists in the scene.
///
[DefaultExecutionOrder(-500)]
public class SingletonMonoBehaviour : MonoBehaviour where T : MonoBehaviour
{
protected static T s_Singleton;
///
/// Gets the singleton instance of the type .
///
public static T Singleton => s_Singleton;
///
/// Creates or returns the singleton instance of type .
///
/// The singleton instance of the type .
public static T CreateSingleton()
{
if (s_Singleton == null)
{
new GameObject(typeof(T).Name, typeof(T));
}
return s_Singleton;
}
protected virtual void Awake()
{
if (s_Singleton != null)
{
Debug.LogWarning($"[SingletonMonoBehaviour] There has been an instance already! {typeof(T).Name}");
Destroy(this);
return;
}
s_Singleton = this as T;
if (gameObject.transform.parent == null)
DontDestroyOnLoad(gameObject);
}
protected virtual void OnDestroy()
{
if (s_Singleton == this as T)
{
s_Singleton = null;
}
}
}
///
/// A simple thread-safe singleton class for non-MonoBehaviour types.
///
public class Singleton where T : class, new()
{
static readonly Lazy _lazyInstance = new();
///
/// Gets the singleton instance of the type .
///
public static T Instance => _lazyInstance.Value;
}
}