hellbound/Assets/Sources/Feel/MMTools/Tools/MMSingletons/MMSingleton.cs

48 lines
971 B
C#
Raw Permalink Normal View History

2021-11-26 11:16:25 +03:00
using UnityEngine;
namespace MoreMountains.Tools
{
/// <summary>
/// Singleton pattern.
/// </summary>
public class MMSingleton<T> : MonoBehaviour where T : Component
{
protected static T _instance;
public static bool HasInstance => _instance != null;
/// <summary>
/// Singleton design pattern
/// </summary>
/// <value>The instance.</value>
public static T Instance
{
get
{
if (_instance == null)
{
_instance = FindObjectOfType<T> ();
if (_instance == null)
{
GameObject obj = new GameObject ();
_instance = obj.AddComponent<T> ();
}
}
return _instance;
}
}
/// <summary>
/// On awake, we initialize our instance. Make sure to call base.Awake() in override if you need awake.
/// </summary>
protected virtual void Awake ()
{
if (!Application.isPlaying)
{
return;
}
_instance = this as T;
}
}
}