- Home /
Need Help Scripting a Highscore System
Hi,
I am currently working on a game that requires storing highscores for the user, that will display at the beginning of the scene and save over the previous time if the new one is better. I am trying to use player preferences, but I am having little luck. In a nutshell, this code is not saving the values to the player preferences, and i don't know why. Is it something obvious or is there something that i am forgetting.Here is my current code:
var myTimer: float=2.0;
var GameCollision : String;
var myTime : float=2.0;
var reciver : int;
static var score : int = 0;
var highscore : int = 0;
function Update ()
{
if( reciver==0 ) {
Highscore = PlayerPrefs.GetInt("High Score");
guiText.text = highscore.ToString();
myTimer+=Time.deltaTime;
WaitForSeconds(5);
guiText.text = myTimer.ToString();
}
}
function OnCollisionEnter (myCollision : Collision) {
if(myCollision.gameObject.name == (GameCollision) & reciver == 0 )
{
myTime=myTimer;
guiText.text = myTime.ToString();
reciver=1;
if( score > PlayerPrefs.GetInt("High Score")) {
PlayerPrefs.SetInt("High Score", score);
highscore = score;
}
}
}
Also, does it make any difference if i am trying to implement this with multiple levels?
Thanks in advance.
Answer by utAlpha09 · Mar 04, 2013 at 02:51 AM
Guess i didn't. In a nutshell, this code is not saving the values to the player preferences, and i don't know why. Is it something obvious or is there something that i am forgetting.
You should add content to your question by using the "add new comment" button rather than as an answer. By adding it as a answer, it is marked as answered and it will receive less traffic. You can use the "more" dropdown to change it to a comment.
As for your question, I cannot pinpoint your specific problem, but the code is a bit strange. Typically the high score would be loaded in a Start(). And the new high score would be set at the end of a level and/or in OnApplicationQuit(). You are getting or setting the score every frame. I don't know the structure of your game, but I don't see anything that is incrementing the score.
Note I also read (but cannot remember where) that the preference are not written out to the permanent store immediately after they are set.