(Unity6_BRP)UIで得点を画面に表示する

(UIの設定)

  • 「Canvas」の上で右クリック→「UI」→「Legacy」→「Text」をクリック

  • 名前を「ScoreLabel」に変更

  • 「Width」と「Height」は「文字を表示できる領域」なので、少し広めにすること(ポイント)
  • 「Text」 ・・・>文字の内容は何でもOK(例;Score等)
  • 「Font Size」・・・>文字の大きさは自由
  • 「Color」・・・>文字の色も自由

  • Canvasの四隅のいずれかに移動させる(場所は自由)


(スクリプトの改良)

  • 「RayController」スクリプトを改良します。
  • ランダムワープするBoxをうまくクリックするたびごとに得点が入るようにします。
using UnityEngine;
// ★追加(得点)
using UnityEngine.UI;

public class RayController : MonoBehaviour
{
    public AudioClip sound;

    // ★追加(得点)
    public Text scoreLabel;
    private int score = 0;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        // ★追加
        scoreLabel.text = "得点: " + score;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            if (Physics.Raycast(ray, out hit))
            {
                GameObject target = hit.collider.gameObject;

                if (target.CompareTag("Box"))
                {
                    // ★改良
                    // Destroyのコードを停止させる(コメントアウトのテクニック)
                    //Destroy(target.gameObject);

                    // ★追加(得点)
                    // Boxをうまくクリックすると50点が入る。
                    score += 50;
                    scoreLabel.text = "得点: " + score;

                    AudioSource.PlayClipAtPoint(sound, Camera.main.transform.position);
                }
            }
        }
    }
}

(実行確認)

  • RayControllerオブジェクトを選択
  • 空欄に「ScoreLabel」を追加

  • 設定が完了したらゲームを再生
  • 初期の得点は「0」

  • Boxを上手くクリックするごとに得点が増加すれば成功です。