I'm making a 2D top-down game, and I'm currently trying to implement a checkpoint system. The checkpoint saves the scene the player was in correctly, and it saves the player's X and Y coordinates. However, when respawning, the player does not go to the right location and instead goes to the spawnpoint of the scene. It may be a simple fix, as I am relatively new to game design, but I've been stuck on this for at least a month now.
I have tried a number of ways to get the player to read the saved locations. The checkpoint location saves correctly in PlayerPrefs, and I have tested it multiple times proving that the values save.
This is my respawn function:
public void Respawn()
{
string lastLevel = PlayerPrefs.GetString("savedScene");
lastCheckPointPos.x = PlayerPrefs.GetFloat("savedX");
lastCheckPointPos.y = PlayerPrefs.GetFloat("savedY");
player.transform.position = new Vector3(lastCheckPointPos.x, lastCheckPointPos.y, 0);
print("respawing");
SceneManager.LoadScene(lastLevel);
}
At first I tried setting the player's individual X and Y values to the saved ones in separate lines of code, setting player.transform.x to savedX and so on, but this did not work. I searched around online and saw that it should work if I put it as a new Vector3, which made sense, but this did not work either. Again, the problem is NOT with saving to PlayerPrefs, the player just cannot seem to read the variables.
Any insight on this would be greatly appreciated as this is the last big roadblock holding me back from continuing progression on the game.
whenever you do SceneManager.LoadScene(lastLevel) Your scene / values reset to their original value, there is no sense in reloading the scene after reading values because they will just be reset.
The way to do it would be to load the scene first then load the settings/positioning