- Home /
How can I save highscores and display them for later?
This is my script. I'am able to get the final score in the game but as an int, but my highscore canvas won't show up nor will my score text's update. I also want to display the highscores on a different scene that could be accessed in the main menu. Sorry if I made any beginner mistakes.
Here is my code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Scores : MonoBehaviour
{
public Text yourCurrentScoreNumberText;
public Text score1;
public Text score2;
public Text score3;
public Canvas HighScoreCanvas;
private TreeBehavior treeBehavior;
public GameObject ScoreCounter;
// GameObject[] trees = GameObject.FindWithTag("Tree");
// Start is called before the first frame update
void Start()
{
HighScoreCanvas.enabled = false;
}
public void ShowHighScoreCanvas()
{
if (ScoreCounter.GetComponent<ScoreCounter>().mängLäbi == true)
{
HighScoreCanvas.enabled = true;
//score componenti peab panema
yourCurrentScoreNumberText.text = ScoreCounter.GetComponent<ScoreCounter>().finalScore.ToString();
int score1st = PlayerPrefs.GetInt("bestscore");
if (score1st < ScoreCounter.GetComponent<ScoreCounter>().finalScore)
{
//old best was smaller, so we save the new best
PlayerPrefs.SetInt("bestscore", ScoreCounter.GetComponent<ScoreCounter>().finalScore);
score1st = ScoreCounter.GetComponent<ScoreCounter>().finalScore;
}
else
{
score1.text = score1st.ToString();
}
}
}
// Start is called before the first frame update
// Update is called once per frame
void Update()
{
}
}
Answer by Roger_0123 · Apr 02, 2020 at 06:00 PM
Hello, if you want to access your highscores you have two possibilities:
1) Use DontDestroyOnLoad: in your Scores script, just call DontDestroyOnLoad(gameObject)
so this object will not be destroyed when changing scene. Note that if you return later on the game scene another Scores object will be instatiated, so you will get two Score objects. To handle this, you may use
void Start(){ //code if(FindObjectsOfType().lenght > 1){ Destroy(gameObject); } }
In any case, this scores are lost when you quit the game.
2) If you want to save your scores in a file, I link here a beautiful tutorial by Brackeys
If your highscores don't come up maybe you have to call HighScoreCanvas.setActive(true)
which is different from enabled
Hope this helps!
Your answer
Follow this Question
Related Questions
PlayerPref set int and get int 1 Answer
Timer highscore trouble 1 Answer