Class 6 - Score, Currency & Upgrades
本节课承接上一节课(Class 5)的 UI 与生命值系统,继续完善 SpaceShooter 的“ 游玩逻辑”:得分、货币与五项升级功能,并完成按钮事件绑定与最终测试。
Class 6 Overview
- 得分与货币系统
- 五项升级功能(Repair、Hull Strength、Fire Speed、Missile Speed、Multiplier)
- 按钮事件绑定
- 最终测试清单
1. 得分与货币系统(GameController)
GameController.cs
using TMPro;
public class GameController : MonoBehaviour
{
public static GameController instance;
// 记得要在Inspector中拖拽赋值哦
public TMP_Text textScore;
public TMP_Text textMoney;
public int score = 0;
public int money = 0;
void Update() {
UpdateDisplay();
}
void UpdateDisplay() {
textScore.text = score.ToString();
textMoney.text = money.ToString();
}
public void EarnPoints(int amount) {
score += amount;
money += amount;
}
}
接下来转到Projectile.cs,在击毁陨石时,也就是在OnCollisionEnter2D函数中加上:调用刚写的EarnPoints()函数
Projectile.cs
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.GetComponent<Asteroid>() != null)
{
Destroy(other.gameObject);
Destroy(gameObject);
GameObject explosion = Instantiate(
GameController.instance.explosionPrefab,
transform.position,
Quaternion.identity
);
Destroy(explosion, 0.25f);
// 加这里!!得分 & 加钱逻辑
GameController.instance.EarnPoints(10);
}
}
2. 五项升级功能
2.1 Repair(Ship)
Ship.cs
public void RepairHull()
{
int cost = 100;
if (GameController.instance.money >= cost && health < maxHealth && health > 0)
{
GameController.instance.money -= cost;
health = maxHealth;
imageHealthBar.fillAmount = health / maxHealth;
}
}
然后我们需要去 Button 的 Inspector 里面,找到 OnClick 事件。把 Ship 对象拖过来绑定,就可以获取到它身上携带的脚本,从而可以选择RepairHull()。
这样做的意思就是:当按钮被点击时,调用Ship身上的RepairHull()函数。

2.2 Hull Strength(Ship)
Ship.cs
using TMPro;
namespace SpaceShooter
{
public class Ship : MonoBehaviour
{
// 记得拖拽赋值
public TMP_Text hullUpgradeText;
public void UpgradeHull() {
// 升级费用等于当前血量上限
int cost = Mathf.RoundToInt(healthMax);
if(GameController.instance.money >= cost) {
GameController.instance.money -= cost;
health += 50;
maxHealth += 50;
imageHealthBar.fillAmount = health / maxHealth;
hullUpgradeText.text = "Hull Strength $" + Mathf.RoundToInt(maxHealth);
}
}
}
}
同上,OnClick 绑定 UpgradeHull()。
String + int?
hullUpgradeText.text = "Hull Strength $" + Mathf.RoundToInt(maxHealth);
我们在这行代码可以看到,text作为一个字符串类型的对象,却可以通过 string + int 的形式实现拼接:
这是因为C#中,字符串在拼接的时候,会自动将不是字符串的类型加一个ToString()转换为字符串类型,这被称之为隐式类型转换。