【Unity6】Adding button click handling

This article can be read in about 4 minutes.
PR

The purpose 

I’ll show you how to execute a specific process when a button is pressed in Unity.

While there are many Japanese articles on this topic (likely for Unity 20XX), my attempts didn’t work – either because of my approach or because it’s incompatible with Unity 6.

This describes a method that works in Unity 6.

PR

Implementation

Register code

In the Hierarchy, select ‘Create Empty’ from the ‘+’ to create an empty GameObject.

Select an empty GameObject created from the Hierarchy view and open its Inspector.

In the Inspector, at the bottom, select Add Component, then choose New Script and give it a name.

The script is modified as follows and then saved. 

using System.Collections;
using System.Collections.Generic;

using UnityEngine;
using UnityEngine.UI;

public class Example : MonoBehaviour
{
    public Button m_Button;

    void Start()
    {
        m_Button.onClick.AddListener(() => ButtonClicked(42));//クリック時の関数を登録 42は任意の引数
    }
    void ButtonClicked(int buttonNo)////引数は必要な型に変更可能
    {
        Debug.Log("Button clicked = " + buttonNo);///ログ出力
        /*クリック時の処理*/
    }
}

create and register button

Create a Canvas by selecting UI → Canvas from the “+” in the Hierarchy view. (This is unnecessary if you already have one.)

Then, create a button by selecting UI → Button – TextMeshPro from the “+” in the Hierarchy view.

Select the empty GameObject you registered the code to above in the Hierarchy view.

Then, drag and drop the button you created from the Hierarchy view onto the Button field that appears in the GameObject’s Script.

PR

Result

Upon execution and button press, logs were output to the Console view. 

The official website, which I also consulted, describes other methods for registering functions. This documentation details the most versatile method. For other options, please refer to the link below.

PR

Reference

UI.Button-onClick - Unity スクリプトリファレンス
ボタンが押されたときに発生する UnityEvent

comment

Copied title and URL