I am having trouble with DontDestroyOnLoad() and scene reloading.
I have this script :
public class SingleInstance : MonoBehaviour
{
private static Dictionary<string, GameObject> instances = new Dictionary<string,GameObject>();
void Awake()
{
GameObject inst = null;
instances.TryGetValue(this.name, out inst);
if (inst == null)
{
DontDestroyOnLoad(this.gameObject);
instances[this.name] = gameObject;
}
else
{
DestroyImmediate(gameObject);
}
}
}
I aplied this script to my UIManager object which is part of a simple 3 object Hierarchy :
UIManager
-ImageLoader -Canvas
(this 3 object hierarchy is a prefab and was dragged and dropped in the scene).
The problem is that after reloading the scene both child objects (the Canvas and ImageLoader) get OnDestroyed called when reloading the scene. In the inspector they still look ok but in code where I access the canvas it says that it is Destroyed with this messge:
MissingReferenceException: The object
of type ‘Canvas’ has been destroyed
but you are still trying to access it.
Your script should either check if it
is null or you should not destroy the
object.
I don’t have any Ideea why the children get “flagged” as destroyed becaus the SingleInstance script only destroys the toBeCreated Object.