using UnityEngine;

namespace Pursuit.Singletons
{
    public abstract class SingletonBehaviour<T> : MonoBehaviour where T : SingletonBehaviour<T>
    {
        private static T _instance;

        public static T Instance
        {
            get
            {
                if (_instance == null)
                {
                    var result = FindAnyObjectByType<T>();

                    // If we can't find an object, don't do anything.
                    // This solves an issue with destruction order when
                    // unloading a scene: other objects in the scene might
                    // want to use the singleton while being destroyed

                    if (result)
                        _instance = result;
                }

                return _instance;
            }
        }
    }
}