using UnityEngine;
using System.Collections;

///<summary>
/// Can be stockpiled on a GameController component.
/// 
/// Adding functions on the delegate with a lambda symbol (above base.Awake when overriding):
///     singletonNonOneSceneEvent += (() => { Debug.Log("Add Functions here!"); });
/// 
/// Remove functions on the delegate:
///     singletonNonOneSceneEvent = null;
///</summary>

public class GenericSingleton<T> : MonoBehaviour where T : Component
{
    public static T instance;

    protected delegate void singletonNonOneSceneDelegate();
    protected singletonNonOneSceneDelegate singletonNonOneSceneEvent;

    protected virtual void Awake()
    {
        if (singletonNonOneSceneEvent != null)
        {
            if (instance == null)
            {
                DontDestroyOnLoad(gameObject);
                singletonNonOneSceneEvent();
            }
            else
            {
                Destroy(gameObject);
                return;
            }
        }
        
        instance = GetComponent<T>();
    }

    protected virtual void OnDestroy()
    {
        if (instance == GetComponent<T>())
        {
            if (singletonNonOneSceneEvent != null)
                singletonNonOneSceneEvent = null;

            instance = null;
        }
    }
}