[英]Unity how to display Highscores 1-9?
我正在做我的团结项目,我的PlayerPrefabs中保存了1-9的高分。 我这样得到他们:
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;
}
但是,如何显示它们呢?
我想我可以为每个高分创建一个文本对象,但是那样会创建很多游戏对象,这似乎是个坏主意。
您应该使用Text
组件而不是OnGUI()
或GUI类中的任何组件。
但是,如何显示它们呢? 我想我可以为每个高分创建一个文本对象,但是那样会创建很多游戏对象,这似乎是个坏主意。
对象池在这里会很好,但是由于您只需要9
文本,因此只需创建Texts
数组即可。 如果要显示高分,请通过调用GetHighScores()
函数加载分数,然后循环遍历Texts
数组并将结果存储到它们。 然后,可以将Text.enabled
设置为true
以显示Texts
。
要隐藏分数,请在Text数组上进行简单循环,然后将每个数字设置为空字符串,然后将Text.enabled
设置为false
。
脚本删除实现了我上面所说的内容。 只需在编辑器中创建9个文本,将“高分”大小更改为9
然后将每个“ Text
”依次拖到“元素”插槽中即可。
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;
}
因为您知道需要存储的数据量为9,所以没有理由使用SortedList
或List
。 您可以只使用array来防止使用SortedList
执行不必要的内存分配。
对于初学者来说,9个文本对象不是很多,但您可以只创建一个,并在不同的行上具有值。
您也可以使用GUI显示该值。
int s1 = 43, s2 = 32;
void OnGUI() {
GUI.Label(new Rect(20, 20, 100, 500), "Score 1: "+s1+"\n Score 2: "+ s2);
}
例如,如果您像在《战地风云》和《使命召唤》中一样按住TAB并启用/禁用它,则也可以创建记分板。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.