unity3d - 关闭和关闭单例模式的问题
问题描述
我目前正在用一个简单的突破游戏测试单例模式。我实现单例模式的方式是这样的。
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); 一开始没有逻辑(?)我对统一和单例模式相当陌生,所以如果有人能指出我正确的方向,那就太好了。
解决方案
推荐阅读
- php - 更改 Laravel Jetstream 应用程序中的徽标
- google-apps-script - 使用脚本Google表格将数据从一个单元格范围移动到另一个单元格
- deep-learning - 在pytorch中训练后如何清除显卡内存?
- node.js - 为什么我正在抓取的 div 是空的
- drools - 流口水,事件发生后添加等待
- youtube-api - 通过 API 上传到 Youtube 时超出上传限制,但可以在后台上传
- javascript - 将部分的孩子放入数组中
- fluid-framework - AssertionError:不安全地转换为只读状态
- python - 在python中以不等间隔加入不同长度的列表?
- c - 在c中获取距离2的邻居图邻接列表