您的位置:首页 > 移动开发 > Unity3D

Unity3D的单例模式实现

2017-03-13 17:12 253 查看

using UnityEngine;

public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>{

 

 private static T m_Instance = null;

   

 public static T instance{

        get{

   if( m_Instance == null ){

             m_Instance = GameObject.FindObjectOfType(typeof(T)) as T;

                if( m_Instance == null ){

                    m_Instance = new GameObject("Singleton of " + typeof(T).ToString(), typeof(T)).GetComponent<T>();

      m_Instance.Init();

                }

              

            }

            return m_Instance;

        }

    }

    private void Awake(){

  

        if( m_Instance == null ){

            m_Instance = this as T;

        }

    }

 

    public virtual void Init(){}

 

    private void OnApplicationQuit(){

        m_Instance = null;

    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: