DontDestroyOnLoad()

Right now, I have a DontDestroyOnLoad function on two of my game objects. I have three scenes, and I only want the two game object stay for one transition, but when the game gets to the final scene, I want the game objects deleted. How do I exactly pick which scenes I want this to happen to.

One way would be by checking the name of the level :

if(Application.loadedLevelName == "FinalScene"){
//delete your gameObjects.
}
1 Like

Try OnLevelWasLoaded.

http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnLevelWasLoaded.html

You can tagged the two other objects you want destroyed in the later scenes like this

    void Awake () {

        GameObject[] GameObject;
       
        GameObject= GameObject.FindGameObjectsWithTag ("TaggedObjects");

        foreach (var i in GameObject)
           
            Destroy (i);
   
    }
}

SWEET! Thank you guys soo much, I got it to work!

Personally I’d create an object that manages these, something like MasterManager. Then have a script on this that checks if your DontDestroyOnLoad objects are spawned, if not spawn them. Using a manager would be better as you’d be able to keep track of how many are in the scene, destroy them, spawn them, edit them.

1 Like