我有一个’SingletonManager’类,带有’LevelManager’单例的实例(以及它的接口). ‘LevelManager’GameObject不应该在整个应用程序生命周期中持久存在,并且每次加载新级别时都应该用新实例替换.
在运行我当前的代码时,当第二次加载场景时,尽管游戏对象(附带脚本)在场景中,但“LevelManager”似乎丢失了.我意识到这可能是因为我仍在尝试访问旧的引用.
每次加载新级别时,确保我的’SingletonManager’保存’LevelManager’的新实例的最佳方法是什么?
SingletonManager:
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;
}
}
}
解决方法:
我从你的问题中理解的是,你需要一个新的对象,因为游戏阶段是变化的,
如果我理解正确,那么这可能对你有所帮助.
为您的解决方案尝试Multiton模式.
这是一个例子
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;
}
}
}
注意: – 我只给你一个例子,不是你班级的完美代码
参考链接:http://en.wikipedia.org/wiki/Multiton_pattern