0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Unity初心者向け:onClick.AddListener() とは?

0
Last updated at Posted at 2025-07-12

はじめに

UnityのUIボタン(Buttonコンポーネント)には onClick というイベントがあって、
AddListener() を使って関数(メソッド)を使うと、クリックしたときにその関数が実行されるようになります。

目次
1.Buttonの作り方
2.スクリプトをかく
3.スクリプトをButtonオブジェクトにアタッチする
4.完成!

1.Buttonの作り方

Hierarchy上で右クリック→UI→Legacy→Button

スクリーンショット 2025-07-12 0.24.33.png

Buttonの位置がすごいことになっていると思うので画像のようにRect Transformを調整します
スクリーンショット 2025-07-12 10.14.34.png

2.スクリプトをかこう

ボタンを押したらHello Worldと表示させるスクリプトを書いてみましょう。

using UnityEngine;
using UnityEngine.UI;  // UIを使う場合に必要

public class OnClick : MonoBehaviour
{
    public Button myButton;  // Inspectorからアタッチする

    void Start()
    {
        // ボタンがクリックされたら、PrintMessage を実行
        myButton.onClick.AddListener(PrintMessage);
    }

    void PrintMessage()
    {
        Debug.Log("Hello, World!");
    }
}


こんな感じでかきます。

3.スクリプトをButtonオブジェクトにアタッチする

1.Hierarchy上にあるButton(Legacy)をクリック
2.Inspectorに先ほど書いたスクリプト(OnClick)をドラッグ&ドロップするもしくはAdd ComponentからOnClickを検索して追加する
3.MyButtonにButton(Legacy)をドラッグ&ドロップするもしくはNone(Button)の右側にある◉をおしてButton(Legacy)を選択

スクリーンショット 2025-07-12 10.10.05.png
スクリーンショット 2025-07-12 10.06.59.png

4.完成

1.実行ボタンをクリックする
2.Buttonをクリックする
3.ConsoleにHello, World!と表示されたら成功!!
スクリーンショット 2025-07-12 10.17.21.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?