Reputation: 1580
I'm working on my unity project and I have high-scores from 1-9 saved in my PlayerPrefabs. I get them like this:
private SortedList<string, int> GetHighScores()
{
SortedList<string, int> tempList = new SortedList<string, int>();
for (int i = 1; i < 10; i++)
{
string tempName = "Highscore " + i;
tempList.Add(tempName, PlayerPrefs.GetInt(tempName));
}
return tempList;
}
However, how can I display them in a good way?
I guess I could create 1 text object for each high-score, but that would create a lot of games objects and seems like a bad idea.
Upvotes: 0
Views: 984
Reputation: 125245
You should be using the Text
component not OnGUI()
or anything from the GUI class.
However, how can I display them in a good way? I guess I could create 1 text object for each high-score, but that would create a lot of games objects and seems like a bad idea.
Object Pooling would have been fine here but, since you only need 9
texts, simply create arrays of Texts
. When you want to show high scores, load your scores by calling the GetHighScores()
function, then loop over the array of Texts
and store the result to them. You can then set Text.enabled
to true
to show the Texts
.
To hide the scores, simple loop over the Text array then set each one to empty string then set Text.enabled
to false
.
The script deblow implements what I said above. Just create 9 texts from the Editor, change High Scores size to 9
and drag each Text
to the Element slots in order.
public Text[] highScores;
public void hideHighScore()
{
for (int i = 0; i < 9; i++)
{
highScores[i].text = "";
highScores[i].enabled = false;
}
}
public void showHighScore()
{
SortedList<string, int> hScores = GetHighScores();
for (int i = 0; i < 9; i++)
{
string tempName = "Highscore " + (i + 1);
highScores[i].text = hScores[tempName].ToString();
highScores[i].enabled = true;
}
}
private SortedList<string, int> GetHighScores()
{
SortedList<string, int> tempList = new SortedList<string, int>();
for (int i = 1; i < 10; i++)
{
string tempName = "Highscore " + i;
tempList.Add(tempName, PlayerPrefs.GetInt(tempName));
}
return tempList;
}
Since you know the amount of data you need to store which is 9, there is no reason to use SortedList
or List
. You can just use array for that and prevent the unnecessary memory allocation performed while using SortedList
.
Upvotes: 1
Reputation:
For starters 9 text objects isn't that much but you could make just one and have the values on different lines.
You could also display the value with GUI.
int s1 = 43, s2 = 32;
void OnGUI() {
GUI.Label(new Rect(20, 20, 100, 500), "Score 1: "+s1+"\n Score 2: "+ s2);
}
You can also create a scoreboard if for example you are holding down TAB like in Battlefield and Call Of Duty and enable/disable it.
Upvotes: 0