Menu
CoddyTech

分数和生命值

Coddy Unity 游戏:打砖块 课程的第 9 课,共 19 课。

分数和生命值应该显示在屏幕上。现在,场景中有一个 Canvas,顶部有两个 TextMeshPro 文本,ScoreText 和 LivesText,GameManager 在 TMPro 命名空间中用 TMP_Text 字段保存它们。

数字保存在 GameManager 的字段中,文本只负责显示它们。一个方法会根据字段内容重写这两个文本,每个修改数字的方法都会调用它,Start() 也会调用它,这样第一帧显示的就是真实数值。商店的金币计数器:

public TMP_Text coinsText;
int coins;

public void AddCoins(int amount)
{
    coins += amount;
    ShowCoins();
}

void ShowCoins()
{
    coinsText.text = "Coins: " + coins;
}

只有数字变化时,文本才会更新。在每次 Update() 中重写文本看起来效果一样,但每一帧都会白白创建一个新字符串。

challenge icon

挑战

中等

在屏幕上显示分数和生命值。

  1. 在 GameManager 中,添加 using TMPro;、public TMP_Text scoreText; 和 public TMP_Text livesText;
  2. 编写 void ShowHud():scoreText.text = "Score: " + score; 和 livesText.text = "Lives: " + lives;
  3. 在 Start 末尾、BrickBroken 中和 BallLost 中调用 ShowHud()。

按下 “开始”:屏幕上会显示 Score: 0 和 Lives: 3,并且这两个数值会随着你玩游戏而变化。然后点击 “检查”。

亲手试试

using UnityEngine;

public class GameManager : MonoBehaviour
{
    public static GameManager Instance;

    public Brick brickPrefab;
    public Transform wall;
    public int rows = 5;
    public int columns = 9;
    public float spacingX = 1.75f;
    public float spacingY = 0.75f;
    public float topY = 6f;
    public int[] rowHits = { 2, 1, 1, 1, 1 };
    public int lives = 3;

    int score;

    void Awake()
    {
        Instance = this;
    }

    void Start()
    {
        BuildWall();
    }

    void BuildWall()
    {
        float left = -(columns - 1) * spacingX / 2f;
        for (int row = 0; row < rows; row++)
        {
            for (int col = 0; col < columns; col++)
            {
                Vector3 pos = new Vector3(left + col * spacingX, topY - row * spacingY, 0f);
                Brick brick = Instantiate(brickPrefab, pos, Quaternion.identity, wall);
                brick.SetHits(rowHits[row]);
            }
        }
    }

    public void BrickBroken(Brick brick)
    {
        score += brick.points;
    }

    public void BallLost(Ball lost)
    {
        lives--;
        lost.ResetToPaddle();
    }
}

Unity 游戏:打砖块中的所有课

自己练习: Unity 在线编辑器