using UnityEngine;

namespace MiaoJuWxSDK.Singleton
{
    public class MIAOJUSingletonMonoBehaviour<T> : MonoBehaviour where T : MIAOJUSingletonMonoBehaviour<T>
    {
        public static T Instance
        {
            get
            {
                return MIAOJUSingletonMonoBehaviour<T>.CreateInstance();
            }
        }

        public static T CreateInstance()
        {
            if (MIAOJUSingletonMonoBehaviour<T>.instance == null)
            {
                MIAOJUSingletonMonoBehaviour<T>.instance = (T)((object)UnityEngine.Object.FindObjectOfType(typeof(T)));
                if (MIAOJUSingletonMonoBehaviour<T>.instance == null)
                {
                    string name = typeof(T).Name;
                    UnityEngine.Debug.LogFormat("Create singleton object: {0}", new object[]
                    {
                        name
                    });
                    GameObject gameObject = new GameObject(name);
                    Object.DontDestroyOnLoad(gameObject);
                    MIAOJUSingletonMonoBehaviour<T>.instance = gameObject.AddComponent<T>();
                    if (MIAOJUSingletonMonoBehaviour<T>.instance == null)
                    {
                        UnityEngine.Debug.LogWarning("Can't find singleton object: " + typeof(T).Name);
                        UnityEngine.Debug.LogError("Can't create singleton object: " + typeof(T).Name);
                        return (T)((object)null);
                    }
                }
            }
            return MIAOJUSingletonMonoBehaviour<T>.instance;
        }

        public static bool IsInstantiated()
        {
            return MIAOJUSingletonMonoBehaviour<T>.instance != null;
        }

        protected void Awake()
        {
            if (this.CheckInstance())
            {
                this.AwakeValidly();
            }
        }

        protected virtual void AwakeValidly()
        {
        }

        private bool CheckInstance()
        {
            if (MIAOJUSingletonMonoBehaviour<T>.instance == null)
            {
                MIAOJUSingletonMonoBehaviour<T>.instance = (T)((object)this);
                DontDestroyOnLoad(this.gameObject);
                return true;
            }
            if (MIAOJUSingletonMonoBehaviour<T>.Instance == this)
            {
                return true;
            }
            UnityEngine.Object.Destroy(this);
            return false;
        }

        protected void DontDestroyOnLoad()
        {
            UnityEngine.Object.DontDestroyOnLoad(base.gameObject);
        }

        private static T instance;
    }
}