そういうのがいいブログ

アプリ個人開発 まるブログ

アプリ開発覚え書き

【Unity】押したボタンを取得してその子のテキストを変更する方法

内容

押したボタンを取得してその子のテキストを変更する方法(タイトル長い)
を開発用にメモ

using System;
using UnityEngine;
using UnityEngine.EventSystems;//追加
using UnityEngine.UI;//追加

public class ChangeButtonText : MonoBehaviour {

    // eventSystem型の変数を宣言 インスペクターにEventSystemをアタッチして取得しておく
    [SerializeField] private  EventSystem eventSystem;
   
    //GameObject型の変数を宣言 ボタンオブジェクトを入れる箱
    private GameObject button_ob;

    //GameObject型の変数を宣言 テキストオブジェクトを入れる箱
    private GameObject NameText_ob;

    //Text型の変数を宣言 テキストコンポーネントを入れる箱
    private Text name_text;



    //ボタンにこの関数を割り当てて使用
     public void ChangeButtonTextName()
    {
        //押されたボタンのオブジェクトをイベントシステムのcurrentSelectedGameObject関数から取得 
        button_ob = eventSystem.currentSelectedGameObject;
        
        //ボタンの子のテキストオブジェクトを名前指定で取得 この場合Text100と名前が付いているテキストオブジェクトを探す
        NameText_ob = button_ob.transform.Find("Text100").gameObject;

        //テキストオブジェクトのテキストを取得
        name_text = NameText_ob.GetComponent<Text>();

        //テキストを変更
        name_text.text = "変更後の文字列";        
    }
}

追記

有効なイベントシステムを↓で取得できるようなので少し改善

EventSystem.current;

使い所:導入したアセット等にEventSystemコンポーネントが入っていた時

イベントシステムが2つ以上あった場合、どちらか1つしか有効にならず、
無効なイベントシステムを参照している可能性があるため、
有効なイベントシステムを使う必要がある.

using System;
using UnityEngine;
using UnityEngine.EventSystems;//追加
using UnityEngine.UI;//追加

public class ChangeButtonText : MonoBehaviour {

    // eventSystem型の変数を宣言 
    private  EventSystem eventSystem;
   
    //GameObject型の変数を宣言 ボタンオブジェクトを入れる箱
    private GameObject button_ob;

    //GameObject型の変数を宣言 テキストオブジェクトを入れる箱
    private GameObject NameText_ob;

    //Text型の変数を宣言 テキストコンポーネントを入れる箱
    private Text name_text;



    //ボタンにこの関数を割り当てて使用
     public void ChangeButtonTextName()
    {
        //有効なイベントシステムを取得
        eventSystem=EventSystem.current;

        //押されたボタンのオブジェクトをイベントシステムのcurrentSelectedGameObject関数から取得 
        button_ob = eventSystem.currentSelectedGameObject;
        
        //ボタンの子のテキストオブジェクトを名前指定で取得 この場合Text100と名前が付いているテキストオブジェクトを探す
        NameText_ob = button_ob.transform.Find("Text100").gameObject;

        //テキストオブジェクトのテキストを取得
        name_text = NameText_ob.GetComponent<Text>();

        //テキストを変更
        name_text.text = "変更後の文字列";        
    }
}

他の記事

marumaro7.hatenablog.com

Unity本を出版しました!

突然ですが、Unity本を出版しました!
こちらを読むことで、スクリプトの基礎固めができます!
現在、kindle unlimitedで読み放題設定中です。今のうちにどうぞ!


もっと早く教えてほしかった!Unity C#入門

参考

note.com

dkrevel.com