- Home /
How to I create a high score using GUIText?
Hello, I am fairly new to Unity3d and am trying to create a highscore system. I would like to have two GUIText on the screen. One would have the current score and the other your highscore. Once the score passes the highscore the score GUIText will disappear and the highscore will count up. This is the script:
pragma strict
var player : Transform;
function Update ()
{
var dist : int = Vector3.Distance(player.position, transform.position);
print ("Distance : " + dist);
var score : int = dist / 10;
guiText.text = "Score : " + score;
if(score > PlayerPrefs.GetInt("highscore"))
{
PlayerPrefs.SetInt("highscore",score);
guiText.text = "Highscore : " + score;
}
}
What am I doing wrong? Thanks in advanced!
Getting and Setting PlayerPrefs every update is a bad idea.
Get them in Start().
var highScore : int = PlayerPrefs.GetInt("highscore");
Then in update:
Update(){
if(score>highScore){
highScore = score;
guiText.text = "High Score : " + highScore.ToString();
}
}
You can then set in OnDisable();
function OnDisable()
{
PlayerPrefs.SetInt("highscore", highScore);
PlayerPrefs.Save();
}
So:
var player : Transform;
function start ()
{
var highScore : int = PlayerPrefs.GetInt("highscore");
}
function Update ()
{
var dist : int = Vector3.Distance(player.position, transform.position);
print ("Distance : " + dist);
var score : int = dist / 10;
guiText.text = "Score : " + score;
if(score>highScore)
{
highScore = score;
guiText.text = "High Score : " + highScore.ToString();
}
Shouldn't I put "var highScore : int = PlayerPrefs.GetInt("highscore");" before "function Start ()"
Declare var highscoree : int;
outside of the start function and then set it in start: highScore : int = PlayerPrefs.GetInt("highscore");
Answer by fifthknotch · Mar 06, 2014 at 04:45 AM
Score is an int. Text can only be string values. To change an int to string use`score.ToString()`
Answer by nazia08 · Mar 08, 2014 at 05:53 AM
Make sure When entering text into the Text property, you can create a line break by holding Alt and pressing Return.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
problem with weapon animation -.- 0 Answers
swapping weapons 1 Answer
Switching between one or more cameras in the same scene? 2 Answers