removing player duplicates after scene transition
Whenever my player switches between scenes, like a house to the outside, my player is duplicated. So, I added these lines of code.
private static bool playerExists;
void Start () {
if (playerExists) {
Destroy(gameObject);
} else {
playerExists = true;
DontDestroyOnLoad(transform.gameObject);
}
}
This does remove the player, but it removes both players, the original and the duplicate. If anyone knows why this happens and how I can fix my problem, I would really appreciate it.
Or, if anyone knows how to remove player duplicates after a player changes scenes, that would work too. My player controller script - http://pastebin.com/S3LdQa8S and my load new scene script - http://pastebin.com/1zegHvj1
Thanks!
If both your scenes contain a player, why are you setting it to no be destroyed when you transition scenes (DontDestroyOnLoad)? Seems like the easiest way to fix this is to just allow the player to be destroyed with the scene.
Thanks for your comment! It seems like it might work, but as I'm new to Unity, could you explain that process in simple terms for me?
Answer by TBruce · Jun 15, 2016 at 09:54 PM
Remove the whole
if (playerExists) {
Destroy(gameObject);
} else {
playerExists = true;
DontDestroyOnLoad(transform.gameObject);
}
thing.
Why do you feel you need it. If it is to have your data carry over from scene to scene then you should consider using PlayerPrefs (or a similar alternative) to save and restore the data.
Answer by cdnDave · Jun 15, 2016 at 09:39 PM
Posted this as answer but apparently it's waiting for a moderator to approve it...
When changing scenes in Unity the default behaviour is for all objects in the current scene to be destroyed before the next scene is created. By calling DontDestroyOnLoad(transform.gameObject); you are telling unity not to destroy the player when changing scenes. If your second scene also has a player object in it then you will now have two players, one from the first scene that never got destroyed and the one that's in the second scene.
I would try removing that call and letting the player be destroyed when you change scenes unless there's a particular reason you need that player to persist across scenes. Essentially I'd remove this whole block.
if (playerExists) {
Destroy(gameObject);
} else {
playerExists = true;
DontDestroyOnLoad(transform.gameObject);
}
Your answer
Follow this Question
Related Questions
Application.loadlevel adding double scripts to objects 0 Answers
Solid Object in 2D 1 Answer
How I can change the sprite of the image because the code doesn't work? 1 Answer
Strangely Transparent Sprites 0 Answers
Scale Sprite like UI Canvas 1 Answer