敵を倒すとスコアアップ!
ダメージを食らうとスコアダウン…
というようなスコア機能が欲しいですよね。
今回はそんなスコア機能の実装方法を紹介していきたいと思います。
準備
・canvasを用意(ヒエラルキーで右クリック>UI>Text-TextMeshPro)

テキストを画面サイズに適応させるために「Canvas Scaler」の「UI Scale Mode」を「Scale With Screen Size」に変更しておきましょう。

CanvasとTextの名前を変更し、位置をときます。


・増減用のボタンをそれぞれ用意

スコアのシステムを実装
スコアの増減のソースコード
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class Score : MonoBehaviour
{
int score;
int ScoreDownAmount = -10;
int ScoreUpAmount = 10;
TMP_Text Scoretext;
void Start()
{
Scoretext = GetComponent<TMP_Text>();
Scoretext.text = "0";
}
public void IncreaseScore()
{
score += ScoreUpAmount;
Scoretext.text = score.ToString();
}
public void DecreaseScore()
{
score += ScoreDownAmount;
Scoretext.text = score.ToString();
}
}
このソースコードをキャンバスの中にあるテキストにアタッチします。

次に、ボタンがクリックされた時に呼び出す関数を設定します。
スコアを増加する関数を呼び出すように、スコア増加プログラムがあるオブジェクトを項目に入れます。

スコア増加ができる関数を設定

この設定をスコア減少ボタンにもしましょう。
これで実行してみますと
このように、スコアの増減ができました!
まとめ
重要な部分
public void IncreaseScore()
{
score += ScoreUpAmount;
Scoretext.text = score.ToString();
}
public void DecreaseScore()
{
score += ScoreDownAmount;
Scoretext.text = score.ToString();
}
この記事ではボタンを押したらスコアが変動するようにしていますが、敵を倒したらスコア増加関数を呼び出してスコアをアップさせたり、攻撃を受けたらスコア減少関数を呼び出してスコアをダウンといったこともできますので皆さんのゲームにも昇華させましょう!
コメント