首页 > 解决方案 > 关闭和关闭单例模式的问题

问题描述

我目前正在用一个简单的突破游戏测试单例模式。我实现单例模式的方式是这样的。

using UnityEngine;

public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
    //Check if about to be destroyed
    private static bool bShutOff = false;
    private static object oLock = new object();
    private static T oInstance;

    public static T Instance
    {
        get
        {
            // First check if this object is OFF 
            if (bShutOff)
            {
                Debug.LogWarning("Singleton instance '" + typeof(T) + "' already destroyed. Returning null.");
                return null;
            }

            lock (oLock)
            {
                if (oInstance == null)
                {
                    //Search for exissting instance 
                    oInstance = (T)FindObjectOfType(typeof(T));

                    // If it still doesn't find one, it creates a new one 
                    if (oInstance == null)
                    {
                        // Creates a game object to attach the singleton 
                        var oSingletonObject = new GameObject();
                        oInstance = oSingletonObject.AddComponent<T>();
                        oSingletonObject.name = typeof(T).ToString() + "(Singleton)";

                        // Make the instance persisten in the world 
                        DontDestroyOnLoad(oSingletonObject);
                    }

                }

                return oInstance;
            }
        }
    }

    private void OnApplicationQuit()
    {
        bShutOff = true;
    }


    private void OnDestroy()
    {
        bShutOff = true;
    }

}

并且该模式被一个名为 GameSession 的类使用(删除了一些可见性代码)

using UnityEngine;
using TMPro;

public class GameSession : Singleton<GameSession>
{
    // Avoids non-singleton construuctor use
    protected GameSession() { }

    // config params 
    [Range(0.1f, 2f)] [SerializeField] float fGameSpeed = 1f; // Range le añade un rango maximo un valor serializado
    [SerializeField] int nPointsPerBlock = 50;
    [SerializeField] TextMeshProUGUI tScore;

    // State variables
    [SerializeField] int nCurScore = 0;


    void Start()
    {
        tScore.text = nCurScore.ToString();
    }

    // Update is called once per frame
    void Update()
    {
        Time.timeScale = fGameSpeed; // normal time
    }

    public void AddScore()
    {
        nCurScore += nPointsPerBlock;
        tScore.text = nCurScore.ToString();
    }

}

起初它没有问题,但是一旦对象被破坏(通过进入不同的场景),布尔值 bShutOff 设置为 True(预期),但由于 bShutOff 为 True,代码的其他功能都不起作用并且我收到调试消息“Debug.LogWarning("Singleton instance '" + typeof(T) + "' already destroy. Returning null.");" (如果对象应该关闭,也可以预期)我猜这是因为 DontDestroyOnLoad(oSingletonObject); 一开始没有逻辑(?)我对统一和单例模式相当陌生,所以如果有人能指出我正确的方向,那就太好了。

标签: unity3dsingleton

解决方案


推荐阅读