Unityの2Dゲームで「プレイヤーの上にダメージを表示」していきます。
敵の攻撃が当たった時などに、プレイヤーの上に数字を表示する感じです。今回は「画面に数字を表示」する部分の実装なので、敵の攻撃やプレイヤーのライフ部分は無いです。
はじめに
Unityのバージョンは2021.3.14f1です。
下記のように、プレイヤーの上にダメージ数を表示してみます。

実装開始
まずはキー操作で動くプレイヤーを作成、その後ダメージの実装をしていきます。
プレイヤーの作成
「Create Empty」で空のオブジェクトを2つ追加。PlayerとGroundに名前を変更します。

それぞれ、下記のように設定します。

PlayerMoveのスクリプトは下記の様な感じ。
using UnityEngine; public class PlayerMove : MonoBehaviour { private float PlayerSpeed = 0.5f; private Rigidbody2D _rigidbody; void Start() { _rigidbody = GetComponent<Rigidbody2D>(); } void Update() { float InputX = Input.GetAxisRaw("Horizontal"); _rigidbody.velocity = new Vector2(InputX * PlayerSpeed, 0); } }
下記が参考記事になります。
実行してみて、地面の上をプレイヤーがキー操作で動けばOK
ダメージテキストの追加
「UI」→「Legacy」→「Text」を追加。

Canvasのレンダーモードをカメラに変更し、カメラをセット。

Textの幅、高さ、フォントサイズを調整。テキストは仮の値を入れておきます。

下記の様な感じですね。

ダメージのスクリプト作成
Damageと言う名前で新規スクリプトをアタッチ、スクリプトの中身は下記です。
using UnityEngine; using UnityEngine.UI; public class Damage : MonoBehaviour { private float _displaytime = 0.4f; private float _timer; private Text _txt; private void Awake() { _txt = GetComponent<Text>(); } void Update() { _timer += Time.deltaTime; if (_timer > _displaytime) Destroy(gameObject); } public void SetDamageText(int value) { _txt.text = value.ToString(); } }
一定時間表示したらオブジェクトを削除、ダメージ量はSetDamageTextでセットします。
オブジェクト名をDamageに変更して、プレハブ化しておきます。

プレハブを出したり消したりしてダメージを表示します。
プレハブ管理を追加
次にダメージのプレハブを呼び出すマネージャを追加します。空オブジェクトを追加してDamageManagerと言う名前に変更します。

DamageManagerと言う名前で新規スクリプトを作成、スクリプトの中身は下記です。
using UnityEngine; public class DamageManager : MonoBehaviour { [SerializeField] private GameObject _damageobj; [SerializeField] private Canvas _canvas; [SerializeField] private Transform _target; public void TakeDamage(int damageval) { Vector2 pos = new Vector2(_target.position.x, _target.position.y + 1.0f); Damage damageIns = Instantiate(_damageobj, pos, Quaternion.identity, _canvas.transform).GetComponent<Damage>(); damageIns.SetDamageText(damageval); } }
指定位置にプレハブをインスタンス化して、ダメージ量をセットしているという感じです。
アタッチして各変数をセットします。

ダメージボタンの追加
今回はボタンを押したらダメージを食らうようにしてみます。「UI」→「Legacy」→「Button」を追加。

ボタンクリック時に呼び出します。

ボタンを押してプレイヤーの上にダメージが表示されたらOK。

このままだと表示して消すだけなので、少しスクリプトを変更。
using UnityEngine; using UnityEngine.UI; public class Damage : MonoBehaviour { private float _displaytime = 0.4f; private float _timer; private Text _txt; private Vector3 pos; private void Awake() { _txt = GetComponent<Text>(); pos = transform.position; } void Update() { _timer += Time.deltaTime; if (_timer > _displaytime) Destroy(gameObject); pos.y += 0.01f; transform.position = pos; } public void SetDamageText(int value) { _txt.text = value.ToString(); } }
表示されてから数字が上昇して消えるという感じです。