Unityの2Dゲームで「プレイヤーの上にダメージを表示」していきます。
敵の攻撃が当たった時などに、プレイヤーの上に数字を表示する感じですね。今回はあくまでも「画面に数字を表示」する部分の実装なので、敵の攻撃やプレイヤーのライフ部分は無いです。
はじめに
「Unity 2020.3.26f1」ヴァージョンで作成しています。
まずは地面とプレイヤーを用意して、キー操作でプレイヤーが動くようにします。下記記事で詳しく書いてます。
画面は下記の様な感じ。


PlayerMoveのスクリプトは下記の様な感じ。
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMove : MonoBehaviour { [SerializeField] private float PlayerSpeed; private Rigidbody2D _rigidbody; void Start() { _rigidbody = GetComponent<Rigidbody2D>(); } void Update() { float InputX = Input.GetAxisRaw("Horizontal"); _rigidbody.velocity = new Vector2(InputX * PlayerSpeed, _rigidbody.velocity.y); } }
白い四角がプレイヤーで、左右に動くようにしてあります。このプレイヤーの上にダメージを表示してみます。
実装開始
ダメージ表示画面を作成してからスクリプトで実装していきます。
ダメージテキストの追加
UI->テキストを追加。ダメージを表示する部分です。

Canvasのレンダーモードをカメラに変更。

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

下記の様な感じですね。

Textの名前をDamageに変更して、プレハブ化しておきます。このプレハブを出したり消したりしてダメージを表示します。

ダメージのスクリプト作成
DamageプレハブにDamageと言う名前で新規スクリプトをアタッチします。スクリプトの中身は下記。
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Damage : MonoBehaviour { private float _timer; private float _displaytime = 0.4f; void Update() { _timer += Time.deltaTime; if (_timer > _displaytime) Destroy(gameObject); } public void SetDamageText(int value) { GetComponent<Text>().text = value.ToString(); } }
一定時間表示したらオブジェクトを削除するようにしてあります。ダメージ量はSetDamageTextでセット。
プレハブ管理を追加
次にプレハブを呼び出すマネージャを追加します。DamageManagerと言う名前で空のオブジェクトを追加。

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

表示位置となるターゲットは、Player配下に空のオブジェクトを追加して位置を調整。プレイヤーの上に配置します。

今回は仮でボタンを押したらダメージを食らうとしていきます。UI->ボタンを追加して、クリック時に呼び出してみます。

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

このままだと味気ないので、スクリプトで数字を動かしたり、アニメーションで色を変えてみたり。
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Damage : MonoBehaviour { private float _timer; private float _displaytime = 10f; void Update() { Vector3 pos = transform.position; _timer += Time.deltaTime; if (_timer > _displaytime) Destroy(gameObject); pos.y += 0.01f; transform.position = pos; } public void SetDamageText(int value) { GetComponent<Text>().text = value.ToString(); GetComponent<Animation>().Play("damage"); } }