WMS
WMS

Reputation: 41

How to access the value of a text field in Unity(5.6.0)?

I'm working on creating an app with Unity, and every time I try to google a question I get old answers or answers that don't work.

What I've got in my unity hierarchy is

 Canvas >
   Panel >
    Text
    SubPanela >
      Button1
      Button2
      Text1
    SubPanelb > 
      Button1
      Button2
      Text2

I need to access and change/replace the string in both the Text 1 and Text 2 panels with a click of one of the buttons. Every method I've tried from my search results has failed spectacularly.

What I'm trying to do is this: If you press Button1 in SubPanela it should take the string in Text1, parse it to an int, and increment it. Simultaneously, it should parse the string in Text to an int and decrement it.

My question is this: How do I access the Strings in Text, and Text1?

Upvotes: 0

Views: 681

Answers (2)

Instead of storing a reference to each text field, as mcjcloud's answer says, you can also navigate the scene hierarchy.

Assuming this script is attached to the Canvas object...

using UnityEngine;
using UnityEngine.UI;

public class MyClass : MonoBehavior {
    public void ButtonClicked() {
        Transform t = transform.GetChild(0); //Panel
        Transform ta = t.FindChild("SubPanela");
        Text txt1 = ta.FindChild("Text1").GetComponent<Text>();
        Transform tb = t.FindChild("SubPanelb");
        Text txt1 = ta.FindChild("Text2").GetComponent<Text>();
    }
}

If the script is attached to one of the buttons, you can use transform.parent to navigate upwards.

You can use FindChild(...) or GetChild(...) as you see fit. The latter is faster but if your hierarchy is mutable then FindChild will be more robust.

Upvotes: 0

mcjcloud
mcjcloud

Reputation: 371

What you should do is make a public reference to the Text element from inside the class you want to change the text in (or wherever the function that is called on the button click resides). For example:

using UnityEngine.UI;

public class MyClass : MonoBehavior {
    public Text MyTextField;

    public void ButtonClicked() {
        MyTextField.text = "random new text";
    }
}

Upvotes: 1

Related Questions