Skip to content

Instantly share code, notes, and snippets.

@Buravo46
Last active August 7, 2022 16:09
Show Gist options
  • Save Buravo46/9428951 to your computer and use it in GitHub Desktop.
Save Buravo46/9428951 to your computer and use it in GitHub Desktop.
【Unity】数当てゲーム

##【ゲーム概要】

1~9のランダムに決められた数を当てるゲーム.

入力フォームに1~9の値を入力して送信ボタンを押す。

Bigと表示されたら入力した値よりも大きい値である。

Smallと表示されたら入力した値よりも小さい値である。

SUCESSと表示されたら入力した値と一致である。

##【スクリプトの使い方】

ヒエラルキーに

  • 問題であるGUIText
  • 入力するためのゲームオブジェクト

を生成する。

問題であるGUITextにQuizControl.csを付ける。

入力するためのゲームオブジェクトにInputForm.csを付ける

InputForm.csのTargetGUITextは問題であるGUITextを選択する。

using UnityEngine;
using System.Collections;
public class InputForm : MonoBehaviour {
private string text = "";
public GameObject targetGUIText;
private Rect rectTextField;
private float textFieldWidth = 100;
private float textFieldHeight = 30;
private float offsetX = 50;
private float offsetY = 100;
private Rect rectSendButton;
private float sendButtonWidth = 60;
private float sendButtonHeight = 30;
private int inputTextMax = 30;
void Awake (){
rectTextField = new Rect(Screen.width/2 - offsetX, Screen.height/2 + offsetY, textFieldWidth, textFieldHeight);
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnGUI(){
TextInputBox(rectTextField);
}
// 入力欄
void TextInputBox(Rect textField){
// 入力欄
text = GUI.TextField(textField, text, inputTextMax);
// 送信ボタンの座標と大きさ
rectSendButton = new Rect(textField.x + textField.width, textField.y, sendButtonWidth, sendButtonHeight);
// ボタンが押されたら
if(GUI.Button(rectSendButton,"送信")){
// Messageの送信
targetGUIText.SendMessage("ComparisonProcess", text);
// 入力文字のリセット
text = "";
}
}
}
using UnityEngine;
using System.Collections;
public class QuizControl : MonoBehaviour {
private int correctValue = 0;
private string catchText = "";
private int result;
private int min = 1;
private int max = 9;
private string initializeText = "?";
// Use this for initialization
void Start () {
correctValue = Random.Range(min, max+1);
guiText.text = initializeText;
}
// Update is called once per frame
void Update () {
}
// 比較処理
void ComparisonProcess(string text){
catchText = text;
// 例外処理
if(int.TryParse(catchText, out result)){
//正常の時
//resultに結果の値が入っている
if(correctValue == result){
guiText.text = "SUCCESS";
} else if(correctValue < result){
guiText.text = "Small";
} else if(correctValue > result){
guiText.text = "Big";
}
}else{
//エラー時:文字列が整数で無い時(少数の時もエラーになる)
//resultには常に0が入っている
guiText.text = "ERROR";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment