1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Unity】ボタンでオブジェクトの表示・非表示を切り替える方法

Posted at

環境

Unity 2019.4.22f
Windows10

やること

Image from Gyazo

やり方

テキストとボタンを設置
Hierarchy > + > UI > Text
Hierarchy > + > UI > Button

Image from Gyazo

空の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 のスクリプトのコンポーネントに以下のようにアタッチする

Image from Gyazo

以上

最初は非表示ではじめる場合

TEXT オブジェクトの Inspector のチェックマークをはずし、
Image from Gyazo

スクリプトで
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);
        });
    }
}
1
3
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
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?