- Home /
Playerprefs save player position
i was trying to make a alternative script to "this"
here's the script, the GUI's works but it isn't saving, would be happy if somebody could help:)
var playerX : float = 2119.7;
var playerY : float = 20.12;
var playerZ : float = 2770.62;
var playerPosition : Transform;
var player : GameObject;
var inRange = 0;
var onSave : boolean = false;
function Awake () {
PlayerPrefs.SetFloat("playerX",playerX);
PlayerPrefs.SetFloat("playerY",playerY);
PlayerPrefs.SetFloat("playerZ",playerZ);
}
function Start () {
playerPosition.transform.position.x = (PlayerPrefs.GetFloat("playerX"));
playerPosition.transform.position.y = (PlayerPrefs.GetFloat("playerY"));
playerPosition.transform.position.z = (PlayerPrefs.GetFloat("playerZ"));
}
function Update () {
playerX =(playerPosition.transform.position.x);
playerY =(playerPosition.transform.position.y);
playerZ =(playerPosition.transform.position.z);
if(onSave == true){
PlayerPrefs.SetFloat("playerX",playerX);
PlayerPrefs.SetFloat("playerY",playerY);
PlayerPrefs.SetFloat("playerZ",playerZ);
}
}
function OnTriggerEnter () {
inRange = 1;
}
function OnTriggerExit () {
inRange = 0;
}
function OnGUI () {
if(inRange == 1){
if(GUI.Button(Rect(300,40,400,50), "SAVE!!!")){
onSave = true;
}
}
}
function loadstuff () {
playerPosition.transform.position.x = (PlayerPrefs.GetFloat("playerX"));
playerPosition.transform.position.y = (PlayerPrefs.GetFloat("playerY"));
playerPosition.transform.position.z = (PlayerPrefs.GetFloat("playerZ"));
}
Answer by whydoidoit · Jun 26, 2012 at 01:32 PM
It looks to me like your problem is that as soon as you press the button it keeps on saving every frame. Turn off onSave in the Update.
if(onSave == true){
onSave = false;
PlayerPrefs.SetFloat("playerX",playerX);
PlayerPrefs.SetFloat("playerY",playerY);
PlayerPrefs.SetFloat("playerZ",playerZ);
}
Or even better:
function OnGUI () {
if(inRange == 1){
if(GUI.Button(Rect(300,40,400,50), "SAVE!!!")){
PlayerPrefs.SetFloat("playerX",playerX);
PlayerPrefs.SetFloat("playerY",playerY);
PlayerPrefs.SetFloat("playerZ",playerZ);
}
}
}
Please mark the question as answered by clicking the tick next to my answer :)
Answer by Tillomaticus · Jun 26, 2012 at 01:26 PM
hey,
you should add
PlayerPrefs.Save();
to your Update's if, right below the .SetFloats() so unity writes the coords in the PlayerPrefs
That's not recommended during game play and is just belt and braces
whydoidoit isabsolutely right suggesting that the save button should just actually save, not set the boolean flag.