changing player position after scene load
Hi friends,
so, I have 2 scenes: a village and a dungeon scene. The player starts in the village. The dungeon is accessed by a door(collider that calls Level Manager to change the scene) in the village scene and vice versa.
On the door, I have put a "Desired spawn position" variable for the player to be in the new scene, when it changes.
When the player collides with the door inside the dungeon, the desired spawn position is saved on PlayerPrefs, and when the new scene loads, the player script reads the PlayerPrefs and I make a vector3 with the data. I can print these vector3 and they contain the information I want.
The door script is:
public Vector3 playerDesiredPosition;
public int desiredLevel;
private void OnTriggerEnter(Collider other)
{
PlayerPrefs.SetString("PLAYER_POSITION_X", playerDesiredPosition.x.ToString("F2"));
PlayerPrefs.SetString("PLAYER_POSITION_Y", playerDesiredPosition.y.ToString("F2"));
PlayerPrefs.SetString("PLAYER_POSITION_Z", playerDesiredPosition.z.ToString("F2"));
LevelManager.doorUsed = true;
SceneManager.LoadScene(desiredLevel);
}
When the new scene is loaded, the player script runs this method on Start() [its the last thing called on Start]:
private void setPlayerPosition()
{
if (LevelManager.doorUsed == true)
{
print("door used");
float playerPositionX = float.Parse(PlayerPrefs.GetString("PLAYER_POSITION_X"));
float playerPositionY = float.Parse(PlayerPrefs.GetString("PLAYER_POSITION_Y"));
float playerPositionZ = float.Parse(PlayerPrefs.GetString("PLAYER_POSITION_Z"));
Vector3 desiredPosition = new Vector3(playerPositionX, playerPositionY, playerPositionZ);
GetComponent().position = Vector3.zero;
GetComponent().position = desiredPosition;
LevelManager.doorUsed = false;
}
else if (LevelManager.doorUsed == false)
{
print("Game started, no door used");
}
The problem is: the player changes its position to something a bit random. It's not the position I wanted. It spawns somewhere else in the terrain.
What could be happening?
Ps.: the player object has a rect transform, but if I do a transform.position I get the same behaviour
Ps2: if the default position of the player prefab is near the door, it works. If its far and 20 units up on Y, it doesnt
Your answer
Follow this Question
Related Questions
How can i get error when failed connect to server? 1 Answer
Null Refrence Expection 2 Answers
C # script taking values from one object and modifying another. 0 Answers
click on object then zoom in 0 Answers