I am new to unity and I am trying to make this game where my score increases according to my character which is moving above and when the character collides with any other gameobject the game resets to the initial level using Application.loadlevel(0). Everything is working fine and i am able to display my score too however i am confused with how will I store my highest score and display it seperately along with my current score. Any help is greatly appreciated. I am trying to figure it out from few hours now. This is the code I wrote.
#pragma strict
// Saving and displaying highest score
private var highestScore : int;
private var currentScore : int;
var scoreText : UI.Text;
function Start()
{
currentScore = Time.time;
PlayerPrefs.GetInt("PrefScore");
highestScore = PlayerPrefs.GetInt("PrefScore");
}
function Update()
{
if (scoreText.name == "ScoreText")
{
scoreText.text = ""+highestScore;
}
PlayerPrefs.SetInt("PrefScore",highestScore);
highestScore = (Time.time-currentScore)*10;
print("Score = "+highestScore);
}
could it be any reason because of using application.loadlevel(0) , is it making my high score reset back to 0 too ?
No, application.load(0) is not the reason of this problem, try this
function Update()
{
if(currentScore > highestScore)
{
PlayerPrefs.SetInt("PrefScore",highestScore);
PlayerPrefs.Save();
}
}
Your code is a bit fuzzy jet, but You definitely not saving the preferences you set.
So
PlayerPrefs.Save()
is your hero
You can take a look at Unity - Scripting API: PlayerPrefs or just serialize your own data somewhere.
I’d recommend using a separate class that holds the data for all the players + their highest score (If that’s what you want)
public class Playerscore
{
public Playerscore(Player p, float Hscore)
{
Player = p;
if(HighestScore < Hscore) {HighestScore = Hscore;}
}
Player player;
float HighestScore;
public void NewScore(float score)
{
if(score > HighestScore) { HighestScore = score; }
}
}
//Serialize this class or the list in this class
public class ScoreBoard
{
public ScoreBoard(){PlayerScore = new List<Playerscore>();}
public List<Playerscore> PlayerScores;
public HighestScore
{get{PlayerScores.Aggregate(0,(x, y) => x > y ? x : y);}}
public getScore (Player p)
{
PlayerScore ps = PlayerScores.FirstOrDefault(x => x.Player == p);
if(ps!=null) { return ps.HighestScore; } return null;
}
public void newScore (Player p, float score)
{
PlayerScore ps = PlayerScores.FirstOrDefault(x => x.Player == p);
if(ps == null)
{
PlayerScore = new PlayerSCore(p, score);
PlayerScores.Add(PlayerScore);
}
else
{
ps.newScore(score);
}
}
Might have some compile errors as I wrote this directly in the comment section instead of an IDE
It should give you a general idea of how to handle scoring though.
Just serialize and deserialize the List as it holds the player data.
Be sure “Player” isn’t a monodevelop as you can’t serialize that.
If it is, rather use a name or unique ID and use those to match the player object.