1
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?

スクリプトからUIボタンに命令(メソッド)を追加する方法

Posted at

onClick.AddListener();関数を用いて、ボタンUIオブジェクトにメソッドを追加する方法を紹介したいと思います。

ボタンにスクリプトをアタッチしてメソッドを追加する方法

button.cs
using UnityEngine;
using UnityEngine.UI;

public class button1 : MonoBehaviour
{
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        GetComponent<Button>().onClick.AddListener(() => { Debug.Log("OnClick"); });
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

Debug.Log("OnClick");の部分が、追加したい任意のメソッドになります。

コントローラスクリプトにボタンをアタッチする方法

button.cs
using UnityEngine;
using UnityEngine.UI;

public class GameController : MonoBehaviour
{
    [SerializeField] Button Button;
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        Button.onClick.AddListener(() => { Debug.Log("OnClick"); });
    }

    // Update is called once per frame
    void Update()
    {

    }
}

[SerializeField]を付けた変数にインスペクターからボタンをアタッチしてください。
スクリーンショット (1).png

以上

1
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
1
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?