Hello I’m trying to create a basic game in which the player runs through a level and is penalised each time they hit an object. Whenever they hit an object their score goes up by 1.
Here’s the script I’m using for scoring:
var score = 0;
var scoreText = "Number of hits: ";
var mySkin : GUISkin;
var saveScoreScript : RecordScore;
function Start(){
saveScoreScript = GetComponent(RecordScore);
}
function OnTriggerEnter( other : Collider ) {
Debug.Log("OnTriggerEnter() was called");
if (other.tag == "obstacle1") {
Debug.Log("Other object is obstacle1");
score += 1;
}
else if (other.tag == "obstacle2") {
Debug.Log("Other object is obstacle2");
score = Mathf.Max(0, score + 1);
}
if (other.tag == "obstacle3" && score > 0) {
Debug.Log("Other object is obstacle3");
score = Mathf.Max(0, score + 1);
}
scoreText = "Score: " + score;
Debug.Log("Number of hits: " + score);
saveScoreScript.AddScore(score);
}
function OnGUI () {
GUI.skin = mySkin;
GUI.Box (Rect (140, 10, 500, 200), scoreText.ToString());
}
I’m saving the player’s score, if it’s lower than their previous, with this script I’ve named RecordScore (as the line var saveScoreScript : RecordScore; shows):
function AddScore(score : int){
if(PlayerPrefs.GetInt("NumberOfHits") > score)
PlayerPrefs.SetInt("NumberOfHits",score);
}
And I’m using this script to display the player’s best score, basically the lowest amount of times they’ve hit an object, next to their current score in the same scene:
var LowestNumberOfHitsAchieved : int;
var mySkin : GUISkin;
var scoreText = "Lowest Number of Hits: ";
function Update(){
LowestNumberOfHitsAchieved = PlayerPrefs.GetInt("NumberOfHits");
}
scoreText = "Lowest Number of Hits: " + PlayerPrefs.GetInt("NumberOfHits");
function OnGUI () {
GUI.skin = mySkin;
GUI.Box (Rect (445, 5, 500, 200), scoreText.ToString());
}
The only thing is that the player’s best score (Lowest Number of Hits: ) isn’t being updated , it constantly reads as 0 I think because 0 is the lowest score the player can have. Let’s say the player runs through the level for the first time and achieves a score of 30. The second time they play their best score should read as 30. As they play the level a second time they achieve a score of 15. So the third time they open up the level their best score should read as 15 (if that doesn’t sound too long winded). But like I said the problem is that their best score isn’t being updated each time they play, it still reads as 0.
I’m not sure where to go from here.
Thank you kindly for any answers or feedback,
-Ben.