using UnityEngine;
using System.Collections;

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

    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 = (Instantiate(Resources.Load(typeof(T).ToString(), typeof(GameObject))) as GameObject).GetComponent<T>() as 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;
            }
        }
    }
}
