I have a 'SingletonManager' class with an instance of the 'LevelManager' singleton (and interface to it). The 'LevelManager' GameObject is not supposed to be persistant throughout the application lifetime and should be replaced with a new instance every time a new level is loaded.
While running my current code, when the scene is loaded for the second time, 'LevelManager' seems to be missing, despite the GameObject (with script attached) being in the scene. I realise that this is probably because I am still trying to access the old reference.
What is the best way to ensure that my 'SingletonManager' holds the new instance of 'LevelManager' every time a new level is loaded?
My code (with irrelevance removed):
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;
}
}
}
Singleton, is not persistant:
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;
}
}
}