- Home /
I want to know how to save high score.
I've made a Brock break game before (it can be said that "long ago..."), and I wanted to save high score in the game and if next player breaks the high score it will be saved until next player breaks the high score, but in my game, the programming isn't working and high score of the game isn't saved. Can someone please tell me how can I solve?
This is my score programming from websites that teaches me a breakout game. using UnityEngine; using UnityEngine.UI;
public class Score : MonoBehaviour
{
public Text scoreText;
public Text highScoreText;
private int score;
private int highScore;
private string highScoreKey = "highScore";
void Start()
{
Initialize();
}
void Update()
{
if (highScore < score)
{
highScore = score;
}
scoreText.text = score.ToString();
highScoreText.text = highScore.ToString();
}
private void Initialize()
{
score = 0;
highScore = PlayerPrefs.GetInt(highScoreKey, 0);
}
public void AddPoint(int point)
{
score = score + point;
}
public void Save()
{
PlayerPrefs.SetInt(highScoreKey, highScore);
PlayerPrefs.Save();
Initialize();
}
}
and this is the code for adding point
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Destroyer : MonoBehaviour
{
public GameObject masterObj;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnCollisionEnter(Collision collision){
masterObj.GetComponent<GameMaster>().boxNum--;
FindObjectOfType<Score>().AddPoint(10);
Destroy(gameObject);
}
}
You need to call Save() function, maybe into the if condition :
if (highScore < score)
{
highScore = score;
Save();
}
Answer by Batuhan13 · Jun 29, 2020 at 10:22 AM
Hi mate I hope you are well =) You could check this brackeys video Brackey video. For saving or storing some values we use Player prefs too you should check that link too =). I hope these will help you =)
If you read the code, $$anonymous$$iyahonmoto is already using PlayerPrefs to save and load the highscore....
Sorry mate my mistake =) I found in that line
PlayerPrefs.SetInt(highScoreKey, highScore);
you have to add (" ") this symbol out of highScoreKey like this
PlayerPrefs.SetInt("highScoreKey", highScore);
no, the current code is correct in that regard because private string highScoreKey = "highScore";
as Hellium pointed out correctly in the comments below the OP the function "Save" is probably just never beeing called upon.