Playerprefs save player position (3940)

I am trying to use playerprefs to save the main character's position. I already was able to save an integer and then load it. I tried multiple ways using playerprefs to save a character's position, but apparently, those ways used too much data with playerprefs, because Unity crashed. Unity worked again after i removed the playerprefs from the scripts. Does anyone know how to save a players position without overloading unity?

3 Answers

3

Saving a few floats won't come anywhere near overloading Unity; something is wrong with the code you wrote. You save the position by writing the x, y, and z coords of the player using PlayerPrefs.SetFloat. If you want to make it a little simpler, you can use ArrayPrefs, which would let you write

PlayerPrefsX.SetVector3 ("PlayerPosition", transform.position);

Assuming `transform` is the transform of the player. Then you load it by doing this:

transform.position = PlayerPrefsX.GetVector3 ("PlayerPosition");

@oz m: It's not "overloading", it's crashing because you're doing something wrong. Post your code, because it's not really possible to say what the problem is without that.

man thaaaaaaaaaaaaaaank you you really help me thank you so mach

On some platforms (especially Android and iOS) it can be really slow to save a lot of data in PlayerPrefs. Sometimes it can take multiple seconds, giving the impression that Unity crashed.

This could be the case if you're saving a lot more than just the player position.

A solution is to write a custom PlayerPrefs class where the data is only saved periodically to a file.

We've shared our own PlayerPrefs class for anyone to download: http://www.previewlabs.com/writing-playerprefs-fast/

here is a working script

#pragma strict
var player : Transform;
var x : float;
var y : float;
var z : float;
function Start () {

 if(PlayerPrefs.HasKey("x") && PlayerPrefs.HasKey("y") && PlayerPrefs.HasKey("z")) {
 
 x = PlayerPrefs.GetFloat("x");
 y = PlayerPrefs.GetFloat("y");
 z = PlayerPrefs.GetFloat("z");
 
 player.position.x = x;
 player.position.y = y;
 player.position.z = z;
 
 }
}

function Update () {

  x = player.position.x;
  PlayerPrefs.SetFloat("x", x);
  
  y = player.position.y;
  PlayerPrefs.SetFloat("y", y);
  
  z = player.position.z;
  PlayerPrefs.SetFloat("z", z);
  
}

anyone know of a java to c# converter? I think I would like to view the functions for this in c#

i think, to use PlayerPrefs.SetFloat in Update function isn't a good idea...