- Home /
[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. :)
Answer by JimmyCushnie · Jan 02, 2018 at 01:58 AM
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.
Answer by Ginxx009 · Jan 02, 2018 at 02:08 AM
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
By making your character a Prefab.
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 -Ginxx009
Thanks. I did just that. I had a bit of trouble with the canvas, but all I needed to do was find the gameObject and get the Canvas component.