Menu
CoddyTech

スコアとライフ

Coddyの「Unityゲーム:ブロック崩し」コースのレッスン 9/19。

スコアと残りライフは画面に表示します。シーンには、画面上部に2つのTextMeshProテキスト、ScoreTextとLivesTextを持つCanvasがあり、GameManagerはTMP_Text名前空間のフィールドとして保持しています。

数値はGameManagerのフィールドに保存され、テキストはその値を表示するだけです。1つのメソッドでフィールドの値から両方のテキストを書き換え、数値を変更するすべてのメソッドがそれを呼び出します。また、最初のフレームで実際の値を表示するため、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プレイグラウンド