LoginSignup
0
1

More than 5 years have passed since last update.

unity > High or Low ゲーム > UI>Textの書き換え / 整数の乱数 / Button選択処理

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

準備

  1. UI > Button を作成し、ButtonHighという名前にする
  2. ButtonHighに下記のMyButton.cs を関連付ける。
  3. ButtonHigh > Button (Script) > On Click()にて ButtonHighを選択する。Functionは MyButton.ButtonClick を選択する。
  4. UI > Text を作成し、TextResultという名前にする。Text (Script)のParagraph > Vertical Overflowを Overflowにして、テキストが長い時に表示が切れないようにする。
  5. ButtonHighをDuplicateして ButtonLowという名前にする。TextをLowにする。

code

MyButton.cs
using UnityEngine;
using System.Collections;
using UnityEngine.UI; // for Text

public class MyButton : MonoBehaviour {
    public Text ResultText;
    public const int kThreshold = 6; // high or low compared with this

    void Judge(bool isHigh) {
        int num = Random.Range (0, 13); // integer random number
        string msg = "Number: " + num.ToString ();

        bool res;
        if (isHigh) {
            msg = msg + ">=" + kThreshold.ToString();
            res = (num >= kThreshold);
        } else {
            msg = msg + "< " + kThreshold.ToString();
            res = (num < kThreshold);
        }

        if (res) {
            msg = msg + ", You Win!";
        } else {
            msg = msg + ", You Lost!";
        }
        ResultText.text = msg;
    }

    public void ButtonClick() {
        switch (transform.name) {
        case "ButtonHigh":
            Judge(/* isHigh=*/ true);
            break;
        case "ButtonLow":
            Judge(/* isHigh=*/ false);
            break;
        default:
            break;
        }
    }
}

実行の様子

Scene_unity_-_game150813_highOrLow_-_PC__Mac___Linux_Standalone__Personal_.jpg

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