[Solved] Storing a GameObject in a var and then instantiating it in a new scene?

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. :slight_smile:

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.

That way, the code will only ever run once.

If you are going to that yes there’s a simple way of doing it.

  1. 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

  1. By making your character a Prefab.

  2. Instantiate the prefab then use the key of your playerprefs to reposition the Prefab you made then make a variable for setting its position.

    transform.position = new Vector3(PlayerPrefs.GetFloat(“PlayerX”), PlayerPrefs.GetFloat(“PlayerY”), PlayerPrefs.GetFloat(“PlayerZ”));

Hope it helps. Happy Coding