動作確認
Unity 5.1.1-f on Mac OS X 10.8.5
準備
- UI > Button を作成し、ButtonHighという名前にする
- ButtonHighに下記のMyButton.cs を関連付ける。
- ButtonHigh > Button (Script) > On Click()にて ButtonHighを選択する。Functionは MyButton.ButtonClick を選択する。
- UI > Text を作成し、TextResultという名前にする。Text (Script)のParagraph > Vertical Overflowを Overflowにして、テキストが長い時に表示が切れないようにする。
- 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;
}
}
}