- Home /
Unity2d - Player wont teleport to the positon after saving x/y positions with player prefs
Hi I am working on a 2d turn based rpg game in unity. I am trying to get unity to save what scene the player was and where the player was inside of the scene after switching back from a fight scene. I have managed to get unity to remember what scene the player was in but the position of the player does not seem to be saved in player prefs. Here is the code for the saving and loading if the players position.
void Start()
{
Player.position = new Vector2(PlayerPrefs.GetFloat("lastPlayerPosX"), PlayerPrefs.GetFloat("lastPlayerPosY"));
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
PlayerPrefs.SetInt("SavedScene", currentSceneIndex);
lastPlayerPosX = Player.position.x;
lastPlayerPosY = Player.position.y;
PlayerPrefs.SetFloat("LastPlayerPositionX", lastPlayerPosX);
PlayerPrefs.SetFloat("LastPlayerPositionY", lastPlayerPosY);
StartCoroutine(Loadscene());
}
IEnumerator Loadscene()
{
anim.SetTrigger("end");
yield return new WaitForSeconds(1.5f);
SceneManager.LoadScene(Scene2Load);
}
}
I serialized the LastplayerX/Y and the values where updating to the players position.
Answer by Eno-Khaon · Aug 03, 2020 at 12:56 AM
Player.position = new Vector2(PlayerPrefs.GetFloat("lastPlayerPosX"), PlayerPrefs.GetFloat("lastPlayerPosY"));
// ...
PlayerPrefs.SetFloat("LastPlayerPositionX", lastPlayerPosX);
PlayerPrefs.SetFloat("LastPlayerPositionY", lastPlayerPosY);
Your Registry entry names/PlayerPrefs variable names are...
lastPlayerPosX
when loading and
LastPlayerPositionX
when saving.
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
How To Do This? 0 Answers
Game Object Teleport's to to players starting position. 3 Answers
Distribute terrain in zones 3 Answers
Want to make a JRPG. 1 Answer