LoginSignup
3
6

More than 5 years have passed since last update.

unity > uGUI > Button > 押したボタンにより異なる処理

Last updated at Posted at 2015-08-13
動作確認
Unity 5.1.1-f on MacOS X 10.8.5

複数のボタンがあり、いずれかを押した時に異なる処理をしたい。

準備

  1. Create > UI > Buttonでボタンを作成する
  2. Buttonの名前をButton1とする
  3. 下記のMyButton.csを作成し、Button1に関連付ける
  4. Button1のButton (Script)のOn Click()にて"+"を押す。Select ObjectにてButton1を選択する。Functionは MyButton.ButtonClickを選択する。

ここまでで1つのボタンを押した時にConsoleに”3.1415"が表示されるようになっている。

続いてButton2, Button3 を追加する。

  1. HierarchyのButton1を選択して、右クリック->Duplicate。Button1(1)が作成される。
  2. Button1(1)の名前をButton2にして、Sceneビュー内で位置をButton1の下などに移動する。Button2 > TextもButton2にするほうがわかりやすい。
  3. 1,2の手順を繰り返して、Button3を作成する。

code

MyButton.cs
using UnityEngine;
using System.Collections;

public class MyButton : MonoBehaviour {
    public void ButtonClick() {
        switch (transform.name) {
        case "Button1":
            Debug.Log ("3.1415");
            break;
        case "Button2":
            Debug.Log("2.7181");
            break;
        case "Button3":
            Debug.Log("6.022 x 10^23");
            break;
        default:
            break;
        }
    }
}

実行の様子

Scene_unity_-_150813_uGUI_List_-_PC__Mac___Linux_Standalone__Personal_.jpg

3
6
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
3
6