最高分
本课属于 Coddy Unity 学习旅程的“打造真正的游戏”单元。第 24 课,共 60 课。
最高分是每局游戏的最佳成绩,因此它保存在 PlayerPrefs 中,只有当一局游戏打破纪录时才会更新。这张弹珠台会在最后一颗球掉落时进行检查:
void GameOver()
{
int best = PlayerPrefs.GetInt("PinballBest", 0);
if (score > best)
{
PlayerPrefs.SetInt("PinballBest", score);
PlayerPrefs.Save();
Debug.Log("New high score: " + score);
}
}正是这个比较让成绩成为最高分。如果没有它,一局游戏得分为 300,而此前的最高分是 5000,那么保存的就会是 300,纪录也就没了。要和已保存的最高分比较,而不是和每局游戏开始时都从 0 开始的值比较:每次重新启动后,未加载任何值的字段都是 0,因此任何分数都能超过它。score > best 会在平分时保留旧纪录,而 score >= best 则会把平分也算作新纪录。
要在游戏过程中显示最高分,请在 Start() 中将它加载到字段里,并显示该字段的值。当一局游戏打破纪录时,同时更新字段、PlayerPrefs 和文本,这样屏幕上显示的分数就始终和保存的值一致。
挑战
中等使用键 BestPoints保存最高分。
- 在
Start()中的ShowBest();上方,写入best = PlayerPrefs.GetInt("BestPoints", 0);。 - 在
EndRound()中的if (points > best)内:设置best = points;,使用PlayerPrefs.SetInt和PlayerPrefs.Save()保存,然后调用ShowBest();和newBestText.SetActive(true);。
按“开始”并给气球打气(按住 Space,再松开),然后点击“停止”再点击“开始”:最高分会保留。然后点击“检查”。
亲手试试
using UnityEngine;
using TMPro;
public class BalloonPump : MonoBehaviour
{
public TMP_Text pointsText;
public TMP_Text bestText;
public GameObject newBestText;
public float pumpRate = 20f;
private float air;
private int points;
private int best;
private bool roundOver;
void Start()
{
ShowBest();
}
void Update()
{
if (roundOver) return;
if (Input.GetKey(KeyCode.Space))
{
air += pumpRate * Time.deltaTime;
transform.localScale = Vector3.one * (1f + air / 50f);
pointsText.text = "Points: " + Mathf.FloorToInt(air);
if (air > 100f)
{
points = 0;
pointsText.text = "Pop! Points: 0";
GetComponent<Renderer>().enabled = false;
roundOver = true;
EndRound();
}
}
else if (Input.GetKeyUp(KeyCode.Space))
{
points = Mathf.FloorToInt(air);
pointsText.text = "Points: " + points;
roundOver = true;
EndRound();
}
}
void EndRound()
{
// 在这里保存新的最高分
}
void ShowBest()
{
bestText.text = "Best: " + best;
}
}
打造真正的游戏中的所有课
自己练习: Unity 在线编辑器