gpt4 book ai didi

c# - 重新加载场景时,如何使我的 Singleton MonoBehaviour 类实例以新实例开始?

转载 作者:行者123 更新时间:2023-11-30 12:46:45 25 4
gpt4 key购买 nike

我有一个“SingletonManager”类,其中包含“LevelManager”单例实例(及其接口(interface))。 “LevelManager”GameObject 不应在整个应用程序生命周期内保持不变,每次加载新级别时都应替换为新实例。

在运行我当前的代码时,当第二次加载场景时,“LevelManager”似乎丢失了,尽管游戏对象(附有脚本)在场景中。我意识到这可能是因为我仍在尝试访问旧引用。

确保每次加载新关卡时我的“SingletonManager”都持有“LevelManager”的新实例的最佳方法是什么?

我的代码(删除了无关紧要的内容):

单例管理器:

public class SingletonManager
{
private static LevelManager instance;
public static ILevelManager Instance
{
get
{
if (this.levelManager == null)
{
this.levelManager = GameObject.FindObjectOfType(typeof(LevelManager)) as LevelManager;
}
return this.levelManager;
}
}
}

单例,不持久:

public class Singleton<Instance> : MonoBehaviour where Instance : Singleton<Instance> {
public static Instance instance;
public bool isPersistant;

public virtual void Awake() {
if(isPersistant) {
if(!instance) {
instance = this as Instance;
}
else {
DestroyObject(gameObject);
}
DontDestroyOnLoad(gameObject);
}
else {
instance = this as Instance;
}
}
}

最佳答案

我从你的问题中了解到,随着游戏阶段的改变,你需要一个新对象
如果我理解正确,那么这可能会对您有所帮助。
为您的解决方案尝试多模式
这是一个例子

class levelManager {
private static readonly Dictionary<object, levelManager> _instances = new Dictionary<object, levelManager>();

private levelManager() {
}

public static levelManager GetInstance(object key) { // unique key for your stage
lock (_instances) {
levelManager instance;
if (!_instances.TryGetValue(key, out instance)) {
instance = new levelManager();
_instances.Add(key, instance);
}
return instance;
}
}
}

注意:- 我只是给你一个例子,对于你的类(class)来说并不是完美的代码
引用链接:http://en.wikipedia.org/wiki/Multiton_pattern

关于c# - 重新加载场景时,如何使我的 Singleton MonoBehaviour 类实例以新实例开始?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18849795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com