今回はUnityで「バナナをクリックしたらカウントする」のを実装していきます。ゲームと呼べるものではないですが、「クリッカーゲームの入門編」見たい感じですね。
はじめに
Unityのヴァージョンは2022.3.14f1です。新規プロジェクトで「2D」を選択し、プロジェクト名は「BananaClone」として作成しています。

画像のバナナは「素材Library様」からダウンロードしておきます。
「Assets」フォルダ内に「Sprites」フォルダを作成します。ダウンロードした画像の中から、透過PNGファイルを入れておきます。画像の名前はbananaに変更しておきます。

実装開始
ここから実際に作成していきます。見た目を作成した後に機能を作成します。
UIの作成
「UI」→「Image」を追加します。

SourceImageにバナナの画像をセットして、「SetNativeSize」を押します。

「UI」→「Legacy」→「Text」を追加します。

位置とテキストを適当に変更しておきます。

下記のような感じに表示できたらOKです。

次にバナナをクリックしたらカウントアップするようにしていきます。
スクリプトでクリック検知とカウントアップ
Assetsフォルダ内にScriptsフォルダを作成します。新規スクリプトの作成をして名前をBananaにします。

スクリプトを開いて、中身を下記に変更します。
using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; public class Banana : MonoBehaviour, IPointerClickHandler { [SerializeField] private Text CountTxt; private int count; public void OnPointerClick(PointerEventData eventData) { count++; CountTxt.text = count.ToString(); } }
バナナ画像をクリックしたときにカウントアップして表示しています。
Imageにスクリプトを追加して、パラメータのテキストをセットします。

実行すると下記のようにバナナをクリックしたら数字がカウントアップします。
