Example of using Player Prefs to save and get a variable

I’ve read all over that I should use Player Prefs for saving my game, but I don’t know how to go about that, could someone post an example script of saving a variable using Player Prefs, and then accessing it again? Thanks, any help would be greatly apprieciated.

From the docs:

var myVariable : float;

PlayerPrefs.SetFloat("Player Score", 10.0);

myVariable = PlayerPrefs.GetFloat("Player Score");

print (myVariable);

Should result in displaying “10.0”.

4 Likes

You will also want to encrypt any data you store in there because it will get hacked and will mess up leaderboards etc. You could also write a class that stores variables from the class as a deliminated string and parse it out and encrypt so you only have to make 2 methods. Such as Store and Retrieve methods that call private encrypt and decrypt methods. Then all you have to do is invoke that class to handle your loading and saving and point references to the variables instead of retrieving from playerPrefs every time you want the data.

Also remember not to use strings as your keys and instead store them for future use. IE it is better to use a static var key = "PLAYER VALUE KEY"; than to use PlayerPrefs.GetString("KEY"); because it will create and destroy a string which will activate the GC.

I would go about encrypting them, but I’m not going to include leaderboards in my game. Partially because I have no idea how to add them. Thanks for the examples and info, it really helped.

You can pretty easily use the AGON or OpenFeint API code. There is ample documentation on this forum and on the development forums of those API’s about getting them to work with Unity.

i have a question of my own about player prefs if may…

can i mentionate then in if statements?

for example , a save and load feature… can i do this?

var checkpoint: float;

PlayerPrefs.SetFloat("stage", 1);

for saving the last location the player was before he closed the aplication and… this:

switch (checkpoint) {

case 0: "teleport to map 0"

break;

case 1: "teleport to map 1"

break;

}

for the load game ? would this work?

Sure, that works. But use an int for that, not a float.

1 Like

thanks! you rock dude… ROCK!

1 Like

i tried but in the load game script… its says that it has no idea what “checkpoint” is

1 Like

If the variable checkpoint is in another script, don’t you have to put something to tell it which script to look in? (I’m guessing).

hmm… well i guess i could use the static comand on the var checkpoint… but that still didnt do anything… he aways read the var as zero value

how can i connect the playerpref with this checkpoint var?

Can you rephrase that all again in English for non-programmer / programming noobs like me? LOL

Dont call your self a noob that just beating your self up

1 Like

Thanks,This helped me after 10 years.

1 Like