Hi. I’m creating a game in which a player can access a menu and jump between multiple scenes. I tried to use DontDestroyOnLoad (), but if I jump to another scene and back, I will have two players. My solution was to instantiate the player on the other scene. I wanted the player to have the attributes (position, rotation, etc) in the other scene. However, it didn’t work. This is my code:
public void LoadSystem (string name) {
GameObject player = GameObject.FindGameObjectWithTag ("Player");
SceneManager.LoadScene (name);
Instantiate (player, player.transform.position, player.transform.rotation);
}
Is there any way I can solve this problem? Or is there a simpler way to do this? Thank you in advance.
You could go back to the version that was working except with duplicate players. Add a static bool called “PlayerInstantiated” or similar. In your method to instantiate the player, first do a check if that bool is true. If so, stop the function. Otherwise, instantiate the player and set PlayerInstantiated to true.
If you are going to that yes there’s a simple way of doing it.
Using PlayerPrefs you can save the position of your character.
By doing this:
//Saving the position of the player
PlayerPrefs.SetFloat("PlayerX", player.transform.position.x);
PlayerPrefs.SetFloat("PlayerY", player.transform.position.y);
PlayerPrefs.SetFloat("PlayerZ", player.transform.position.z);
Note: As for the rotation value just do the same as the position