プログラミング逆引き辞典

~ 多言語対応のプログラミングレシピ ~

Unity3 スクリプトでボタン押下時のイベント作成

■Unityのスクリプトでボタン押下時のイベントを作成する方法
 


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class GameManager : MonoBehaviour
{
    GameObject button;
    // Start is called before the first frame update
    void Start()
    {   
        button = GameObject.Find("Button");
        // クリックした時のイベントメソッドを「Test1」としてセット
        button.GetComponent<Button>().onClick.AddListener(Test1);
    }

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

    }
    // ボタンを押した時のメソッド
    void Test1() {
        Debug.Log("ボタンをクリックした");
    }
}

 

 
 
 
※ちなみにシーン変更の場合は下記のように記述する


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
// シーンを変更する為の名前空間
using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour
{
    GameObject button;
    // Start is called before the first frame update
    void Start()
    {   
        button = GameObject.Find("Button");
        // クリックした時のイベントメソッドを「Test1」としてセット
        button.GetComponent<Button>().onClick.AddListener(Test1);
    }

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

    }
    // ボタンを押した時のメソッド
    void Test1() {
        // シーンを変更
        SceneManager.LoadScene("Test2Scene");
    }
}

 
【注意】シーンをビルドすることを忘れないように