Unityでボタンを作成しています。
下記のプログラムを実行すると、無限ループにハマってしまいます。
詳しい方がいらっしゃいましたらぜひ教えてください。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ButtonScript : MonoBehaviour
{
public GameObject objPrefab;
GameObject[] button = new GameObject[3];
int selected = 0;
void Start()
{
// Inspector ビューで設定したスプライトのプレハブ // ボタンのスプライトのインスタンスの配列
// 選択されているボタン番号
// プレハブから3つのボタンをインスタンス化
for (int i = 0; i < 3; i++)
{
float y = (float)(2 * (1 - i));
button[i] = (GameObject)Instantiate(objPrefab, new Vector3(0, y, 0), Quaternion.identity);
}
// 色を変える
ChangeButtonColor(selected);
}
void Update()
{
// ↓キーが押された場合の処理
if (Input.GetKeyDown(KeyCode.DownArrow))
{
if (++selected > 2)
selected = 0;
ChangeButtonColor(selected);
}
// ↑キーが押された場合の処理
if (Input.GetKeyDown(KeyCode.UpArrow))
{
if (--selected < 0)
selected = 2;
ChangeButtonColor(selected);
}
}
// 選択中のボタンを明るく、それ以外を暗くする
void ChangeButtonColor(int n)
{
SpriteRenderer spriteRenderer;
for (int i = 0; i< 3; i++)
{
spriteRenderer = (SpriteRenderer) button[i].GetComponent<SpriteRenderer>();
spriteRenderer.material.color = (i == n) ? Color.white : Color.grey;
}
}
}
よろしくお願いします。