Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

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

Discussion in 'UI Toolkit' started by aetharra, Dec 19, 2022.

  1. aetharra

    aetharra

    Joined:
    Oct 10, 2021
    Posts:
    7
    If I query for a specific text element, I want to change the text value of the element.

    Code (CSharp):
    1.  VisualElement visualText = root.Q("LabelOne");
    Code (CSharp):
    1.  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.
     
    Last edited: Dec 19, 2022
  2. Neutron

    Neutron

    Joined:
    Apr 25, 2011
    Posts:
    45
    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.
     
  3. aetharra

    aetharra

    Joined:
    Oct 10, 2021
    Posts:
    7
    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.

    Code (CSharp):
    1. : '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.
     
    Last edited: Dec 19, 2022
  4. aetharra

    aetharra

    Joined:
    Oct 10, 2021
    Posts:
    7
    Oh I see the mistake.

    Code (CSharp):
    1. VisualElement visualText = root.Q<Label>("LabelOne");
    needs to be

    Code (CSharp):
    1. Label visualText = root.Q<Label>("LabelOne");
     
    pgs1000 likes this.
  5. C-UITools

    C-UITools

    Unity Technologies

    Joined:
    Jun 23, 2021
    Posts:
    22
    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)
     
    Haxel0rd likes this.