How does unity get the content of button text

Time:2022-5-9

You can get the text content in the button as follows

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
public class ButtonContent : MonoBehaviour{
     public Button btn;
     void Start(){
         btn = GameObject. Find ("fill in button name") getComponent<Button>(); //----------- (1)
         Text text = btn.transform.Find("Text").getComponent<Text>(); //------------(2)
         //Or (1) (2) merge into:
         //  Text text = GameObject. Find ("fill in button name / text") getComponent<Text>();
         Debug.Log(text.text.toString());
         //In fact, it's just a sentence
  //     Debug. Log (GameObject. Find ("fill in button name / text") getComponent<Text>(). text. toString());
     }
}

Supplement: unity gets the text, button and other components of any GameObject node

The core only has one sentence:

Text/Button compo=GameObject. Find ("any button / text node name") GetComponent();

Or:

Text text = gameobject. transform. Find ("text name") GetComponent();

Supplement: how does unity3d modify the text displayed by the button and learn more about the button components

After creating a button, the structure is as follows:

First, take a closer look at the inspector view of the button:

It was found that there was a script component called button

Create a new script with the following code, and bind the script to the canvas component:

using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine;
public class btn1 : MonoBehaviour
{
    // Start is called before the first frame update
   public Button btn;
    void Start()
    {
    }
    // Update is called once per frame
    void Update()
    {
        GameObject go = GameObject.Find("Butt");
        Text text=go.GetComponentInChildren<Text>();
        text. Text = "Tian sang is playing csgo";
        Debug.Log(text.text);
    }
}

1. First pass GameObject Find() finds the game object named butt

2. Get the component of type T under the subdirectory through getcomponentinchildren()

(I’ve tried using getcomponent before, but it doesn’t work because the text of the button is in the subdirectory)

3. We can also get the button component:

GameObject go = GameObject.Find("Butt");
        Button button=go.GetComponent<Button>();
        if(button)Debug. Log ("found this button!");

The combined output of these two codes is:

This indicates that both components have been found

From this view, the structure of the button is clear. The button is in the first level directory and the generated text is in the subdirectory

The experimental results meet the expectations:

The above is my personal experience. I hope I can give you a reference, and I hope you can support developpaer. If there are mistakes or not fully considered, please don’t hesitate to comment.