在Unity3D中使用单例模式

# 起因

通过构造函数的方式实现单例模式在Unity3D中存在问题,因每当挂载的组件被调用时,构造函数会被反复调用。

# 方法

第一步:创建工具类 Singleton

using UnityEngine;

///

/// Inherit from this base class to create a singleton.

/// e.g. public class MyClassName : Singleton {}

///

public class Singleton : MonoBehaviour where T : MonoBehaviour

{

    // Check to see if we're about to be destroyed.

    private static bool m_ShuttingDown = false;

    private static object m_Lock = new object();

    private static T m_Instance;

    ///

    /// Access singleton instance through this propriety.

    ///

    public static T Instance

    {

        get

        {

            if (m_ShuttingDown)

            {

                Debug.LogWarning("[Singleton] Instance '" + typeof(T) +

                    "' already destroyed. Returning null.");

                return null;

            }

            lock (m_Lock)

            {

                if (m_Instance == null)

                {

                    // Search for existing instance.

                    m_Instance = (T)FindObjectOfType(typeof(T));

                    // Create new instance if one doesn't already exist.

                    if (m_Instance == null)

                    {

                        // Need to create a new GameObject to attach the singleton to.

                        var singletonObject = new GameObject();

                        m_Instance = singletonObject.AddComponent();

                        singletonObject.name = typeof(T).ToString() + " (Singleton)";

                        // Make instance persistent.

                        DontDestroyOnLoad(singletonObject);

                    }

                }

                return m_Instance;

            }

        }

    }

    private void OnApplicationQuit()

    {

        m_ShuttingDown = true;

    }

    private void OnDestroy()

    {

        m_ShuttingDown = true;

    }

}

第二步:调整单例类

public class MagicWallManager : Singleton

{

    //

    //  Single

    //

    protected MagicWallManager() { }

    void Awake(){

    … 初始化内容

    }

    。。。

}

使用方式

MagicWallManager.Instance

# REF

http://wiki.unity3d.com/index.php/Singleton

你可能感兴趣的:(在Unity3D中使用单例模式)