查询扩展

使用 ULB 查询扩展,直接从 VisualElement 根元素中查找 UI Toolkit 元素。

UitkQueryExtensions 将 ULB 路径和 GUID 查找功能作为 VisualElement 的扩展方法提供。当需要使用搜索逻辑而不使用 MonoBehaviour 链接器组件时,请使用这些方法。

添加 using DA_Assets.ULB;,以便使用扩展方法和 ElementIndexName。

GetByPath<T>

GetByPath 从指定的根元素开始,沿 ElementIndexName 数组查找。Index = -1 时匹配 Name;其他 Index 值则选择该位置的子元素。

csharp
using DA_Assets.ULB;
using UnityEngine.UIElements;

VisualElement root = uiDocument.rootVisualElement;

Button saveButton = root.GetByPath<Button>(
    new ElementIndexName
    {
        Index = UitkConstants.DEFAULT_INDEX,
        Name = "toolbar"
    },
    new ElementIndexName
    {
        Index = UitkConstants.DEFAULT_INDEX,
        Name = "save-button"
    });

GetByGuid<T>

GetByGuid 递归搜索后代元素,以查找具有指定 GUID 的 ULB IHaveGuid 元素。

csharp
Button saveButton = root.GetByGuid<Button>(
    "9c7f1231e0aa438687d8804d63053783");

GetByGuidHierarchy<T>

GetByGuidHierarchy 沿一条精确的 GUID 层级分支查找。该分支中的每一段都必须是实现 IHaveGuid 的 ULB 元素。

csharp
Button saveButton = root.GetByGuidHierarchy<Button>(
    "5c3a3a122e654af7a349189ae2038771",
    "92f00728d29540ab98223c54348d2cbd",
    "9c7f1231e0aa438687d8804d63053783");

返回值和搜索开销

  • 如果未找到元素,或找到的元素无法转换为 T,这三个方法都会返回 null。
  • GetByGuid 会递归扫描后代元素,直到找到匹配项。
  • GetByPath 和 GetByGuidHierarchy 沿一条已配置的分支查找。
  • GUID 方法需要 ULB *G 元素;普通 UI Toolkit 元素可通过路径或 Unity 的标准 Query API 查找。

完整组件示例

csharp
using DA_Assets.ULB;
using UnityEngine;
using UnityEngine.UIElements;

public sealed class DirectQueryView : MonoBehaviour
{
    [SerializeField] private UIDocument uiDocument;

    private void Start()
    {
        Button button = uiDocument.rootVisualElement.GetByGuid<Button>(
            "9c7f1231e0aa438687d8804d63053783");

        if (button != null)
        {
            button.clicked += OnClicked;
        }
    }

    private void OnClicked()
    {
    }
}