- Home /
DontDestroyOnLoad - is it intended behavior?
Today I found out that DontDestroyOnLoad function clones host gameObject at level reload. It seems to me, that before Unity 3.1 it acted differently (unfortunately I dont have other versions at hand). Is it OK or is it a bug?
It seems that should be the expected behavior, yes? Every time you reload the scene a new 'dummy' object will be created; since each of these objects will persist from level to level, you end up with multiple dummy objects. (A more typical use of DontDestroyOnLoad() would be, I think, to apply it to an object in e.g. scene A, and then progress through scenes B, C, etc. In this context, the single object created in scene A would persist through any subsequently loaded levels.)
Answer by duck · Nov 16, 2010 at 10:33 AM
I think this behaviour was present in previous versions. It is not that DontDestroyOnLoad is cloning the gameObject, it is that the non-destroyable-object is persisting (as it should), but re-loading the level is also loading a new copy of the object (because it exists in the scene file).
If you want to reload the scene which contains the "Don't Destroy" object, but you don't want two copies of that object, you need to add some code which makes the 2nd new copy of the object destroy itself, leaving the first to persist. For example, a static boolean variable could be used to do this:
private var _sofar : float;
private static created = false;
function Awake() {
if (!created) {
// this is the first instance - make it persist
DontDestroyOnLoad(this.gameObject);
created = true;
} else {
// this must be a duplicate from a scene reload - DESTROY!
Destroy(this.gameObject);
}
}
function Update() {
_sofar += Time.deltaTime;
if (_sofar > 3) {
print("reloading level ...");
Application.LoadLevel("test");
}
}
An alternate approach is to not pre-create this persistent "state" object in your hierarchy at all, rather have every scene check if the object exists, and create it dynamically (i.e. using some "LoadState" script), only if it doesn't already exist. This way, you always have just one copy of this object, and it doesn't matter what scene you start in.
duck's way is preferred for better code maintenance, since one only has to care about persistence in one place.
There's also Persistent Singleton patterns that are really good for this.
Answer by ciabaros · Aug 04, 2012 at 10:48 PM
An alternate approach to Ben's answer is to not create this persistent "state" object in your hierarchy at all, and have every scene check if the object exists, and create it dynamically (i.e. using some "LoadState" script), only if it doesn't already exist. This way, you always have just one copy of this object, and it doesn't matter what scene you start in.