How to change UI Toolkit's Text Visual Element in Script?

If I query for a specific text element, I want to change the text value of the element.

 VisualElement visualText = root.Q("LabelOne");
 visualText.text = "New Text Value";

But there is no option to change this. Since the actual text used by the text object is a UXML attribute. And the query only allows access to the USS.

So how do I change the text value at runtime? Or do I have to create multiple text elements and hide and unhide? I would rather just change the text value of one element for a clean UI tree.

Your code should work fine, I don’t understand the problem. You can override any of the styles on an element using code at runtime.

I am not trying to change the style but the actual text of the Label that is used. The editor is telling me that .text is not an option for visual element.

: 'VisualElement' does not contain a definition for 'text' and no accessible extension method 'text' accepting a first argument of type 'VisualElement' could be found (are you missing a using directive or an assembly reference?)

And it lets me change the .name of the element but that doesn’t help me because that isn’t the textfield.

Oh I see the mistake.

VisualElement visualText = root.Q<Label>("LabelOne");

needs to be

Label visualText = root.Q<Label>("LabelOne");
1 Like

A VisualElement is a base class for UIElements objects. If you want to add text to a VisualElement, then it becomes a Label. This label is a Control, which has a text property and associated scripting you can benefit from.

You can find other controls that could be useful to you here: Unity - Manual: Controls (unity3d.com)

1 Like