I use DontDestroyOnLoad(this); on one of my object and when going back and forth between scenes, it spawns multiple same objects because they never destroy. I want that there would be only one object. Is there some particular code to prevent object from spawning at the start of certain scene?
This is a problem with several solutions.
The easiest and most intuitive is to instantiate your dontdestroyonload objects in a scene before the one where they are actively used. That is, you’ll have a “loading” scene. Then you add some logic on your dontdestroy objects that will destroy themselves when they need to. You can add a flag to an object as well to do similar things. The important thing that makes this work is that you don’t go to the loading scene a second time.
This works and will most often get the job done for things like audio. But sometimes you have to go deeper depending on the situation.
The next most common way I tackle this issue is to have an object in my scene that handles instantiating my dont destroy on loaded objects by checking if they already exist or not.
if(GameObject.Find("levelObj(Clone)") == null) {
Instantiate (levelObj);
}
I use the above code to do this.
levelObj is an object that has dontdestroyonload in it.
This script resides on a separate object that isn’t destroyed on load, “levelObj” is a public variable for this code that I define via the inspector.
This script checks if the dontdestroy object already exists. If it already does, don’t create a new one.
Hey Heke,
I believe the problem you’re having is that somewhere in your code you instantiate the object, without checking if it already exists. There are many ways you could fix this, and using a variable would probably be easiest. You could also give your object a tag, and check if the tag exists before instantiating.
I hope I’ve helped. - Gibson
@Heke,
Use Singleton pattern for this object. Simply, destroy object on Start or Awake callbacks if instance of this object already exist.
I give the object a unique tag, then on scene load do a FindObjectWithTag, if no object is found I instantiate the object, otherwise I don’t.