Home > Software design >  How to get child text text via script on button?
How to get child text text via script on button?

Time:03-03

I have a button with a text child object. I have a script on this button. How to get the text of the button's child object through this script?

enter image description here

Here is the script hanging on the button.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class monumentButtonAppy : MonoBehaviour
{   
    public void ButtonPressed()
    {
        // DataHolders.Monument
        SceneManager.LoadScene(3);
    }
}

The received text from the button, I need to apply it to the variable "DataHolders.Monument"

CodePudding user response:

You could drag and drop your text to this [SerializableField] as text object in Unity Editor.

using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class monumentButtonAppy : MonoBehaviour
{   
[SerialiableField] Text text;
public void ButtonPressed()
{
    // DataHolders.Monument
    SceneManager.LoadScene(3);
}
}

CodePudding user response:

This could be another way if you have script on button GameObject

button.gameObject.transform.GetChild(textIndex /*Usually it's 0*/).GetComponent<Text>().text="Hello World"

CodePudding user response:

button.GetComponentInChildren(); Or make a public Text text,and drag your text to it in unity Editor.

  • Related