- Home /
DontDestroyOnLoad( ) Issue with Instantiation
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.
Answer by jenci1990 · Dec 05, 2014 at 07:33 PM
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);
//...
}
Answer by TSRajesh · Dec 05, 2014 at 07:23 PM
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/
Thank you for this. Your answer and jenci's answer together solve my problem but I can only choose one as an answer, sorry! This helped a lot though, thanks.
You're welcome. No problems.. Really doesn't matter which answer is "correct".. We just share knowledge..
Your answer
Follow this Question
Related Questions
Scene loads in editor not in build 0 Answers
One Location Game (with Scenes Loaded and Disabled) 0 Answers
How do I fix lighting glitch between scenes? 1 Answer
I can't figure it out. 1 Answer
Attempting to Create an Essential SceneElements Checker 0 Answers