3
1

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 5 years have passed since last update.

【Unity】テキストのONとOFFを交互に切り替えるボタンを作る

Last updated at Posted at 2020-04-19

環境

Unity 2019.3.7f1

はじめに

ONとOFFが交互に切り替わるボタン作りたいそこのあなた!
今から作ります!

実装までのステップ

全6ステップです。
1.ボタンを作成
2.空のゲームオブジェクトを作成
3.スクリプトを作成
4.空のゲームオブジェクトに作ったスクリプトをアタッチ
5.空のゲームオブジェクトのスクリプトにボタンのテキストをアタッチ
6.ボタンにスクリプトの関数を割り当て

1.ボタンを作成
ボタンを作成したら勝手にCanvasが生成され、その中にボタンが作成されます。
image.png
 
ボタンのテキストをONに変更しておきます。
image.png

2.空のゲームオブジェクトを作成
image.png

3.スクリプトを作成
新規スクリプトを作成しスクリプトの名前は適当にtestとつけます。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;//UIを使うため追加

public class test : MonoBehaviour
{
    [SerializeField] private Text on_off_text;//ボタンのテキストをアタッチ
    private bool on_off_button_bool;//bool型の変数on_off_button_boolを宣言


    void Start()
    {
        on_off_button_bool = true;//初期設定
    }

    //ボタンを押したら実行する関数 実行するためにはボタンへ関数登録が必要
    public void Push_Button_Change()
    {
        on_off_button_bool = !on_off_button_bool;// !で反対の意味にするtrueならfalse 、falseであらばtrueになる。

        //on_off_button_boolがtrueだったら処理
        if (on_off_button_bool == true)
        {
            on_off_text.text = "ON";//テキスト変更
        }

        //on_off_button_boolがtrueではないなら処理
        else
        {
            on_off_text.text = "OFF";//テキスト変更
        }
    }
}

 
4.空のゲームオブジェクトに作ったスクリプトをアタッチ
image.png

5.空のゲームオブジェクトのスクリプトにボタンのテキストをアタッチ
image.png

6.ボタンにスクリプトの関数を割り当て
ボタンオブジェクトのインスペクターのButtonコンポーネントで関数を割り当て
image.png

 
実行結果
ボタンを押すたびにテキストがONとOFFに切り替わります。

おわりに

今回は作業内容だけとしておきます。
もっと簡単にできる方法があると思うので教えてください。

3
1
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?