x


high score using Player Prefs

I got it working so that it will keep track of a score for a certain game but whenever i restart my game the high score goes back to 0. Here is my script and thanks for all the help in advance.

static var hotDogsEaten : int = 0; var mosthotDogsEaten : int = 0; function Update() { print(PlayerPrefs.GetInt("High Score"));

PlayerPrefs.SetInt("Current Score", hotDogsEaten);

PlayerPrefs.SetInt("High Score", mosthotDogsEaten);

if(PlayerPrefs.GetInt("Current Score") > PlayerPrefs.GetInt("High Score")) { PlayerPrefs.SetInt("High Score", hotDogsEaten); }}

// I have a different script that tells when a hot dog is eaten.

more ▼

asked Jul 19 '12 at 03:04 AM

UnityGameMaker1 gravatar image

UnityGameMaker1
1 1 1 2

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

for starters, you don't need to set the PlayerPrefs every frame:

static var hotDogsEaten : int = 0;
var mostHotDogsEaten : int = 0; 

    function Update() { 

    if(hotDogsEaten > PlayerPrefs.GetInt("High Score")) {     
    PlayerPrefs.SetInt("High Score", hotDogsEaten);
    mosthotDogsEaten = hotDogsEaten;
    }
    }

next, when you start up, you'll need to retrieve that info:

function Start(){

mostHotDogsEaten = PlayerPrefs.GetInt("High Score")
}

that's it!

edit: removed unnecessary lines, my bad..

more ▼

answered Jul 19 '12 at 03:18 AM

Seth Bergman gravatar image

Seth Bergman
7k 10 16 28

if(!PlayerPrefs.GetInt("High Score"))

is this a proper statement??? i hope GetInt returns 0 when there is no key present... also these lines

if(!PlayerPrefs.GetInt("High Score")) PlayerPrefs.SetInt("High Score",0);

are not even needed since it is gonna return 0 even if the key is not preset. if you want it more readable you should be using if(!PlayerPrefs.HasKey("High Score"))

Jul 19 '12 at 03:37 AM flamy

ok.. I don't have much experience with PlayerPrefs, so if "if(!PlayerPrefs.HasKey("High Score"))" is available, I'm sure you're right.. My line would work too though.. as for returning 0 on a null value, not so sure.. You MAY be right.. Yep, ok, you're right, just tested.. Just didn't know if it could cause an error to try to retrieve a non-existent value, guess not

Jul 19 '12 at 03:43 AM Seth Bergman

thank you so much, that worked perfectly!

Jul 19 '12 at 02:14 PM UnityGameMaker1
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x302

asked: Jul 19 '12 at 03:04 AM

Seen: 823 times

Last Updated: Jul 19 '12 at 02:14 PM