DontDestroyOnLoad question

Hello forum!

I have two scenes and a character. I want to maintain the position of the character after switching from scenes. Currently it respawns the player in the default position. I tried to attach a DontDestroyOnLoad script to the player but a strange thing happens.

When i switch from the scene, the character is somehow translated at a position below any in-game object and the terrain. The result is that the character falls to infinity. From what i understand i need to save the previous position of my character and feed it back as soon as the scene loads. However i dont know how to do that.

Any examples or help would be greatly appreciated.

Objects that are made persistent with DontDestroyOnLoad have a slight problem. A new instance of the object will be created each time you go back to the scene, but the existing instance will still be there as well. You can check if that is happening here by looking in the Hierarchy panel to see if more than one instance of the player object is there. There are a few ways you might get around this depending on what happens in the game. Typically, you should use the Instantiate function to create the DontDestroyOnLoad object rather than add it directly to the scene. Then, you can check in an “if” statement if the object already exists using GameObject.Find or a static boolean variable and then avoid creating another instance if there is already one in the scene.

As for storing the object’s position, since the script component doesn’t get destroyed at the end of a scene, you can just add a Vector3 variable to it to store the position just before the previous scene ends. There is an OnLevelWasLoaded function that you can use to detect the start of the new scene.