GameObject with a Canvas that has 2 TextMeshProUGUI textfields

I instantiate a prefab that has a canvas with 2 textFields (the canvas is world space and is a child of the instantiated prefab)
If there is only one textfield I can refer it like so:

GameObject b = Instantiate(boxPrefab, pos, transform.rotation);
        Canvas c = b.GetComponentInChildren<Canvas>();
        TextMeshProUGUI txt = c.GetComponentInChildren<TextMeshProUGUI>();
        txt.text = "foo";

But I have two.
How can I insert a value to the first one and a value to the second one.
How can I refer to each textfield by it’s name?

You can find all text fields using GetComponentsInChildren, however a better idea would be to make a monobehavior that stores references to those fields, put it into the root of prefab, and assign references by hand. Then use the stored references from the component.

1 Like

Great!
And after I have an Array of textfields how do I know which is witch?
Do I have to check the tags?
Or threre is a better way

TextMeshProUGUI[] txt = c.GetComponentsInChildren<TextMeshProUGUI>();
        if (txt[0].gameObject.tag == "MO") txt[0].text = "1";

You don’t.

You’ll have to mark them somehow. You COULD assign tags, yest, but it is a roundabout way to do it.

If I were making something like this, I would create a component

public class MenuDialogRoot: MonoBehaviour{
    public TextMeshProUGUI nameEntryField;
    public TextMeshProUGUI codeEntryField;
}

Then I would assign the values in inspector by dragging components onto it, then I’d put it into prefab, and then I’d try to get the component I wrote.

2 Likes