【Unity3D】UI Toolkit elements

1 Introduction

        Introduction to UI Toolkit introduces UI Builder, style attributes, UQuery, and Debugger; UI Toolkit containers  introduce containers such as VisualElement, ScrollView, ListView, and GroupBox; UI Toolkit style selectors  introduces simple selectors, complex selectors, and pseudo-classes Selector and other style selectors, this article will introduce the elements in UI Toolkit, mainly including Label, Button, TextField, Toggle, Radio Button, Slider, Progress Bar, Dropdown, Foldout, etc. For the official introduction, see → UXML elements reference .

2 Label

        For the official introduction of Label, see → UXML element Label .

        1) Attribute introduction

  • View Data Key : Used for view data persistence (such as: tree expansion state, scroll position, zoom level), as a key for saving/loading view data, if this key is not set, the persistence of the element will be disabled.
  • Picking Mode : Determines whether this container can be selected during mouseEvents.
  • Tooltip : The prompt text that pops up when the mouse hovers over the container.
  • Usage Hints : Expected usage patterns, which facilitate the system to speed up certain operations.
  • Tab Index : Used to sort the focus objects in the focus ring.
  • Focusable : Whether the container can get focus. 
  • BindingPath : The path to the target property binding.
  • Text : The text content of the label.
  • Enable Rich Text : Whether to support rich text.
  • Display Tooltip When Elided : Whether the hover tooltip shows the full version of the omitted text.

        Note: View Data Key, Picking Mode, Tooltip, Usage Hints, Tab Index, Focusable, and BindingPath are all base class attributes. If these attributes appear later, they will not be described in detail. 

        2) Rich text application

        When rich text is supported, enter the following rich text in text and it will be displayed as follows.

<b>Hello</b> <color=green>World</color>

3 Button

        For the official introduction of Button, see → UXML element Button .

        1) Attribute introduction

  • Text : The text content of the button.
  • Enable Rich Text : Whether to support rich text.
  • Display Tooltip When Elided : Whether the hover tooltip shows the full version of the omitted text.

        2) Incident response

        ButtonDemo.cs

using UnityEngine;
using UnityEngine.UIElements;

public class ButtonDemo : MonoBehaviour {
    private void Awake() {
        VisualElement root = GetComponent<UIDocument>().rootVisualElement;
        Button button = root.Q<Button>();
        button.clicked += OnClick;
    }

    private void OnClick() {
        Debug.Log("Clicked");
    }
}

4 TextField (input text)

        For the official introduction of TextField, see → UXML element TextField .

        1) Attribute introduction

  • Label : label.
  • Value : Enter text, modifying this value will not trigger an event.
  • Max Length : Enter the maximum length of the text, -1 means the length is not limited.
  • Password : Whether it is a password, if it is a password, it will be displayed using the characters in Mask Character, and "*" will be used by default.
  • Mask Character : When the entered text is a password, replace the displayed characters.
  • Text : Enter text, modifying this value will trigger an event, and the text will be synchronized to value.
  • Readonly : Whether the input text is read-only.
  • Is Delayed : Whether to update the value in a delayed manner. If the update is delayed, the value attribute will not be updated until the user presses Enter or the input text loses focus.
  • Multiline : Whether to allow multi-line input.

        2) Incident response

        TextFieldDemo.cs

using UnityEngine;
using UnityEngine.UIElements;

public class TextFieldDemo : MonoBehaviour {
    private void Awake() {
        VisualElement root = GetComponent<UIDocument>().rootVisualElement;
        TextField textField = root.Q<TextField>();
        textField.isDelayed = true; // 延时更新value, 在用户按Enter或输入文本失焦后才更新value属性
        textField.RegisterValueChangedCallback(OnValueChanged);
    }

    private void OnValueChanged(ChangeEvent<string> e) { // 输入回调事件
        Debug.Log("previousValue=" + e.previousValue + ", newValue=" + e.newValue);
    }
}

5 Toggle (check box)

        For the official introduction of Toggle, see → UXML element Toggle .

         1) Attribute introduction

  • Label : The checkbox label.
  • Value : The checked state of the checkbox.
  • Text : The text behind the checkbox.

        2) Incident response

        ToggleDemo.cs

using UnityEngine;
using UnityEngine.UIElements;

public class ToggleDemo : MonoBehaviour {
    private VisualElement root; // 根容器
    private GroupBox groupBox; // 分组盒子
    private string[] toggleLabel = new string[] {"First", "Second", "Third", "Fourth"}; // toggle的标签

    private void Awake() {
        root = GetComponent<UIDocument>().rootVisualElement;
        groupBox = root.Q<GroupBox>();
        groupBox.text = "ToggleDemo";
        groupBox.style.fontSize = 50;
        root.Add(groupBox);
        for (int i = 0; i < toggleLabel.Length; i++) {
            AddToggle(i);
        }
    }

    private void AddToggle(int index) { // 添加单选项
        Toggle toggle = new Toggle();
        toggle.text = toggleLabel[index];
        toggle.style.fontSize = 50;
        VisualElement ve = toggle.Query<VisualElement>().AtIndex(2);
        ve.style.marginRight = 10;
        toggle.RegisterValueChangedCallback(e => OnValueChanged(index, e));
        groupBox.Add(toggle);
    }

    private void OnValueChanged(int index, ChangeEvent<bool> e) { // value变化回调函数
        Debug.Log("index=" + index + ", previousValue=" + e.previousValue + ", newValue=" + e.newValue);
    }
}

        After running, click Second, Third, as shown below.  

        The print log is as follows.

6 RadioButton (single button)

        For the official introduction of RadioButton, see → UXML element RadioButton .

        1) Attribute introduction

  • Label : radio button label.
  • Value : The checked state of the radio button.
  • Text : The text behind the radio button.

        2) Incident response

        RadioButtonDemo.cs

using UnityEngine;
using UnityEngine.UIElements;
 
public class RadioButtonDemo : MonoBehaviour {
    private VisualElement root; // 根容器
    private GroupBox groupBox; // 分组盒子
    private string[] choiceLabel = new string[] {"First", "Second", "Third", "Fourth"}; // choice的标签
 
    private void Awake() {
        root = GetComponent<UIDocument>().rootVisualElement;
        groupBox = root.Q<GroupBox>();
        groupBox.text = "RadioButtonDemo";
        groupBox.style.fontSize = 50;
        root.Add(groupBox);
        for (int i = 0; i < choiceLabel.Length; i++) {
            AddChoice(i);
        }
    }
 
    private void AddChoice(int index) { // 添加单选项
        RadioButton choice = new RadioButton();
        choice.text = choiceLabel[index];
        choice.style.fontSize = 50;
        VisualElement ve = choice.Query<VisualElement>().AtIndex(2);
        ve.style.marginRight = 10;
        choice.RegisterValueChangedCallback(e => OnValueChanged(index, e));
        groupBox.Add(choice);
    }
 
    private void OnValueChanged(int index, ChangeEvent<bool> e) { // 选项变化回调函数
        Debug.Log("index=" + index + ", previousValue=" + e.previousValue + ", newValue=" + e.newValue);
    }
}

        After running, click Second, as shown below. 

        The print log is as follows.

7 RadioButtonGroup (radio button group)

        For the official introduction of RadioButtonGroup, see → UXML element RadioButtonGroup .

        1) Attribute introduction

  • Label : The radio button group label.
  • Value : The currently selected radio button index.
  • Choices : The text behind the radio button, a string array separated by ",".

        2) Configure the radio button group

        Configure the RadioButtonGroup as follows.

        Expand the RadioButtonGroup, and find that 4 RadioButtons are automatically added under it, as follows. 

        Displayed below.

        3) Incident response

        RadioButtonGroupDemo.cs

using UnityEngine;
using UnityEngine.UIElements;

public class RadioButtonGroupDemo : MonoBehaviour {
    private VisualElement root; // 根容器
    private string[] choices = new string[] {"First", "Second", "Third", "Fourth"}; // choices的标签

    private void Awake() {
        root = GetComponent<UIDocument>().rootVisualElement;
        RadioButtonGroup group = root.Q<RadioButtonGroup>();
        group.label = "";
        group.choices = choices;
        group.style.fontSize = 50;
        group.RegisterValueChangedCallback(OnValueChanged);
    }

    private void OnValueChanged(ChangeEvent<int> e) { // value变化回调函数
        Debug.Log("previousValue=" + e.previousValue + ", newValue=" + e.newValue);
    }
}

        After running, click Second, as shown below. 

        The print log is as follows.

8 Slider and SliderInt (slider)

        For the official introduction of Slider, see → UXML element Slider , and for the official introduction of SliderInt, see → UXML element SliderInt .

        1) Attribute introduction

  • Label : The slider label.
  • Value : The value of the slider.
  • Low Value : The minimum value of the slider.
  • High Value : The maximum value of the slider.
  • Page Size : When the slider is clicked, the amount of change in Value; when the Page Size is set to 0, the slider is clicked, and the value is the sliding value of the mouse position.
  • Show Input Field : Show the value of the slider.
  • Direction : The direction of the slider, the values ​​are Horizontal (horizontal), Vertical (vertical).
  • Inverted : As the value increases, the slider grows in the opposite direction.

        2) Incident response

        SliderDemo.cs

using UnityEngine;
using UnityEngine.UIElements;

public class SliderDemo : MonoBehaviour {
    private VisualElement root; // 根容器

    private void Awake() {
        root = GetComponent<UIDocument>().rootVisualElement;
        Slider slider = root.Q<Slider>();
        slider.style.width = 500;
        slider.RegisterValueChangedCallback(OnValueChanged);
    }

    private void OnValueChanged(ChangeEvent<float> e) { // value变化回调函数
        Debug.Log("previousValue=" + e.previousValue + ", newValue=" + e.newValue);
    }
}

         After running, slide the slider and print the log as follows. 

9 ProgressBar (progress bar)

        For the official introduction of ProgressBar, see → UXML element ProgressBar .

         1) Attribute introduction

  • Low Value : The minimum value of the progress bar.
  • High Value : The maximum value of the progress bar.
  • Title : The title in the middle of the progress bar.

        2) Incident response

        ProgressBarDemo.cs


using System.Collections;
using UnityEngine;
using UnityEngine.UIElements;

public class ProgressBarDemo : MonoBehaviour {
    private VisualElement root; // 根容器
    private ProgressBar progressBar; // 进度条

    private void Awake() {
        root = GetComponent<UIDocument>().rootVisualElement;
        progressBar = root.Q<ProgressBar>();
        progressBar.style.width = 500;
        progressBar.value = progressBar.lowValue;
        progressBar.Query<VisualElement>().AtIndex(2).style.backgroundColor = Color.grey; // 进度条背景色
        progressBar.Query<VisualElement>().AtIndex(3).style.backgroundColor = Color.green; // 进度条颜色
        progressBar.RegisterValueChangedCallback(OnValueChanged);
        StartCoroutine(Progress());
    }

    private IEnumerator Progress() { // 更新进度条
        while (progressBar.value < progressBar.highValue) {
            progressBar.value += 0.2f;
            yield return null;
        }
    }

    private void OnValueChanged(ChangeEvent<float> e) { // value变化回调函数
        Debug.Log("previousValue=" + e.previousValue + ", newValue=" + e.newValue);
    }
}

        Explanation: Here, the progress bar is updated through the coroutine (for the introduction of the coroutine, please refer to → coroutine ), and the progress of the progress bar is printed in OnValueChanged.

        The running effect is as follows.  

10 Dropdown (drop-down list)

        For the official introduction of Dropdown, see → UXML element DropdownField .

         1) Attribute introduction

  • Label : The dropdown list label.
  • Index : The index of the selected option.
  • Choices : The text of the options, an array of strings separated by ",".

        2) Configuration drop-down list

        Configure Dropdown as follows.

         Displayed below.

        3) Incident response

        DropdownDemo.cs

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;

public class DropdownDemo : MonoBehaviour {
    private VisualElement root; // 根容器
    private List<string> choices = new List<string> {"First", "Second", "Third", "Fourth"}; // choices的标签

    private void Awake() {
        root = GetComponent<UIDocument>().rootVisualElement;
        DropdownField dropdown = root.Q<DropdownField>();
        dropdown.style.width = 600;
        dropdown.choices = choices;
        dropdown.RegisterValueChangedCallback(OnValueChanged);
    }

    private void OnValueChanged(ChangeEvent<string> e) { // value变化回调函数
        Debug.Log("previousValue=" + e.previousValue + ", newValue=" + e.newValue);
    }
}

        After running, click Second, as shown below.  

        The print log is as follows.

11 Foldout (folded list)

        For the official introduction of Foldout, see → UXML element Foldout .

        1) Attribute introduction

  • Text : The collapsed list text.
  • Value : The expanded state of the collapsed list, true means expanded, false means contracted.

        2) Add elements

        Drag an element onto Foldout, and it will be automatically placed under its unity-content element, as follows. 

        Displayed below.

        3) Incident response

using UnityEngine;
using UnityEngine.UIElements;

public class FoldoutDemo : MonoBehaviour {
    private VisualElement root; // 根容器
    private Foldout foldout; // 折叠列表
    private string[] items = new string[] {"First", "Second", "Third", "Fourth"}; // items的标签

    private void Awake() {
        root = GetComponent<UIDocument>().rootVisualElement;
        foldout = root.Q<Foldout>();
        for(int i = 0; i < items.Length; i++) {
            AddItems(items[i]);
        }
        foldout.RegisterValueChangedCallback(OnValueChanged);
    }

    private void AddItems(string text) {
        Label label = new Label(text);
        foldout.Add(label);
    }

    private void OnValueChanged(ChangeEvent<bool> e) { // value变化回调函数
        Debug.Log("previousValue=" + e.previousValue + ", newValue=" + e.newValue);
    }
}

        After running, click the folding triangle to print the log as follows.  

Guess you like

Origin blog.csdn.net/m0_37602827/article/details/132634675