- Home /
[Solved] PlayerPrefs Vector 3 Defaulting to 0,0,0
I Wrote A simple code to save position/rotation of the player but i ran into a problem the players position after erasing playerprefs (Have a special button in the menu that deletes playerprefs from the registry) the players position is being set to 0,0,0 and thus starts falling to nothingness. Any ideas on what i did wrong? Thanks!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SaveGame : MonoBehaviour
{
[Tooltip("Assign The PlayerObject To Save Its Position")]
public GameObject Player;//Assign Position.
[Tooltip("Assign The PlayerObject To Save Its Rotation")]
public GameObject RPlayer;//Assign Rotatio.
void Start()
{
float Xpos = PlayerPrefs.GetFloat ("PlayerX");
float Ypos = PlayerPrefs.GetFloat ("PlayerY");
float Zpos = PlayerPrefs.GetFloat ("PlayerZ");
Player.transform.position = new Vector3 (Xpos, Ypos, Zpos);
float Xrot = PlayerPrefs.GetFloat ("RPlayerX");
float Yrot = PlayerPrefs.GetFloat ("RPlayerY");
float Zrot = PlayerPrefs.GetFloat ("RPlayerZ");
float Wrot = PlayerPrefs.GetFloat ("RPlayerW");
Player.transform.rotation = new Quaternion (Xrot, Yrot, Zrot, Wrot);
}
void Update()
{
PlayerPrefs.SetFloat ("PlayerX", Player.transform.position.x); // Saves X position.
PlayerPrefs.SetFloat ("PlayerY", Player.transform.position.y);// Saves y position.
PlayerPrefs.SetFloat ("PlayerZ", Player.transform.position.z);// Saves z position.
PlayerPrefs.SetFloat ("RPlayerX", RPlayer.transform.rotation.x); // Saves X Rotation.
PlayerPrefs.SetFloat ("RPlayerY", RPlayer.transform.rotation.y); // Saves y Rotation.
PlayerPrefs.SetFloat ("RPlayerZ", RPlayer.transform.rotation.z); // Saves z Rotation.
PlayerPrefs.SetFloat ("RPlayerW", RPlayer.transform.rotation.w); // Saves w Rotation.
}
}
If you use GetFloat(look at the documentation and the default values for the second parameter) and there isn't a corresponding key and the default value isn't set it will result in default(float) which is 0.0f. So assu$$anonymous$$g you Set the values, stop the game, start, notice it loads the values you set... you're super happy then use the $$anonymous$$enu item you mention to delete the keys... start/play the game again it will result in all the values being set to zero(0) due to the default value not being set on the GetFloat call.
Answer by SITH-RULER · Nov 09, 2016 at 06:34 PM
Figured Out the problem just added a reference to player.transform.position in the update function itself
X = Player.transform.position.x;
Y = Player.transform.position.y;
Z = Player.transform.position.z;
PlayerPrefs.SetFloat ("X", X);
PlayerPrefs.SetFloat ("Y", Y);
PlayerPrefs.SetFloat ("Z", Z);
and then checked if there were any values in the Corresponding keys by using
if(PlayerPrefs.HasKey("X") && PlayerPrefs.HasKey("Y") && PlayerPrefs.HasKey("Z))
{
// Code to load the position goes here.
}