using UnityEngine;
using System.Collections;

public class SelfInstantiatingSingleton<T> : MonoBehaviour where T : SelfInstantiatingSingleton<T>
{

    protected static T instance;
    public bool persistBetweenScenes;

    public static T Instance
    {
        get
        {
            if (instance == null)
            {
                instance = FindObjectOfType(typeof(T)) as T;
                if (instance == null)
				{
					instance = new GameObject(typeof(T).Name).AddComponent<T>();
				}
            }
            return instance;
        }
    }
	
    protected virtual void Awake()
    {
        if (instance == null)
        {
            instance = this as T;
            if (persistBetweenScenes)
            {
                DontDestroyOnLoad(gameObject);
            }
        }
        else
        {
            if (instance != this)
            {
                Destroy(gameObject);
                return;
            }
        }
    }
	
	protected virtual void OnDestroy()
	{
		if(instance == this && !persistBetweenScenes)
		{
			instance = null;
		}
	}
}
