using System;
using UnityEngine;

public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
{
	private static T instance
	{
		get
		{
			if (MonoSingleton<T>.m_Instance != null)
			{
				return MonoSingleton<T>.m_Instance;
			}
			Type typeFromHandle = typeof(T);
			T t = UnityEngine.Object.FindObjectOfType(typeFromHandle) as T;
			if (t == null)
			{
				string text = typeFromHandle.ToString();
				GameObject gameObject = new GameObject(text, new Type[]
				{
					typeFromHandle
				});
				t = gameObject.GetComponent<T>();
				if (t == null)
				{
					Debug.LogError("Problem during the creation of " + text, gameObject);
				}
			}
			else
			{
				MonoSingleton<T>.Initialize(t);
			}
			return MonoSingleton<T>.m_Instance;
		}
	}

	private static void Initialize(T instance)
	{
		if (MonoSingleton<T>.m_Instance == null)
		{
			MonoSingleton<T>.m_Instance = instance;
			MonoSingleton<T>.m_Instance.OnInitialize();
		}
		else if (MonoSingleton<T>.m_Instance != instance)
		{
			UnityEngine.Object.DestroyImmediate(instance.gameObject);
		}
	}

	private static void Destroyed(T instance)
	{
		if (MonoSingleton<T>.m_Instance == instance)
		{
			MonoSingleton<T>.m_Instance.OnFinalize();
			MonoSingleton<T>.m_Instance = (T)((object)null);
		}
	}

	public virtual void OnInitialize()
	{
	}

	public virtual void OnFinalize()
	{
	}

	private void Awake()
	{
		UnityEngine.Object.DontDestroyOnLoad(base.gameObject);
		MonoSingleton<T>.Initialize(this as T);
	}

	private void OnDestroy()
	{
		MonoSingleton<T>.Destroyed(this as T);
	}

	protected virtual void OnApplicationQuit()
	{
		MonoSingleton<T>.Destroyed(this as T);
	}

	private static T m_Instance;
}
