I currently have two scenes. I have my player prefab in one, that holds the score, weapons collected etc and I want to make it persistent through all the scenes. I tried using DontDestroyOnLoad() but now when I switch from the first scene to the second, the player object gets spawned underneath my map and then falls indefinitely.
I want to know if there’s a way to make sure that whenever I go between my two scenes that the character is re-instantiated in the same place (right in front of the door), and also doesn’t end up with multiple copies of my player object when reloading those scenes multiple times.
If we DontDestroyOnLoad(), we must also make sure that we don’t have a second copy instantiated in the new scene, (And delete it if there is). (web search for singleton in unity).
But when we change scenes, the object’s global postion will remain the same… Which may or may not be appropriate for the new scene. What I do is, explicitly specify the starting location on the startup script of every scene.
Got the link…
http://unitypatterns.com/singletons/
Add this function (or void) to your player script:
function OnLevelWasLoaded (level : int) {
// You can set the start position in different level
if (level == 0) transform.position = new Vector3(0f,0f,0f);
if (level == 1) transform.position = new Vector3(0f,0f,0f);
//...
}