環境
Unity 2019.4.22f
Windows10
やること
やり方
テキストとボタンを設置
Hierarchy > + > UI > Text
Hierarchy > + > UI > Button
空のGameObjectを作る。
Hierarchy > + > UI > Create Empty
作った空の GameObject に以下のスクリプトをアタッチ
ButtonController.cs
using UnityEngine;
using UnityEngine.UI;
public class ButtonController : MonoBehaviour
{
public GameObject textGameObject;
public Button button;
private void Start()
{
bool isActive = true;
button.onClick.AddListener(() =>
{
isActive = !isActive;
textGameObject.SetActive(isActive);
});
}
}
空の Gameobject の Inspector のスクリプトのコンポーネントに以下のようにアタッチする
以上
最初は非表示ではじめる場合
TEXT オブジェクトの Inspector のチェックマークをはずし、
スクリプトで
isActive を falseにする。
こうしないと、最初ボタンを押しても反応しない。
ButtonController.cs
using UnityEngine;
using UnityEngine.UI;
public class ButtonController : MonoBehaviour
{
public GameObject textGameObject;
public Button button;
private void Start()
{
bool isActive = false; //ここ
button.onClick.AddListener(() =>
{
isActive = !isActive;
textGameObject.SetActive(isActive);
});
}
}