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]を付けた変数にインスペクターからボタンをアタッチしてください。