Version: Unity 6.3 LTS (6000.3)
Language : English
Load UXML and USS in C# scripts
Find visual elements with UQuery

Instantiate UXML from C# scripts

To build UI from a UXML file:

  1. Load the file into a VisualTreeAsset,.
  2. Use either:

Once the UXML is instantiated, you can retrieve specific elements from the visual treeAn object graph, made of lightweight nodes, that holds all the elements in a window or panel. It defines every UI you build with the UI Toolkit.
See in Glossary
with UQuery.

The following example creates a custom Editor window and loads a UXML file as its content:

using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
using UnityEditor.UIElements;

public class MyWindow : EditorWindow  {
    [MenuItem ("Window/My Window")]
    public static void  ShowWindow () {
        EditorWindow w = EditorWindow.GetWindow(typeof(MyWindow));

        VisualTreeAsset uiAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/MyWindow.uxml");
        VisualElement ui = uiAsset.Instantiate();

        w.rootVisualElement.Add(ui);
    }
}

To load UXML assets for runtime, set up VisualTreeAsset references in your MonoBehaviour scripts and assign the UXML assets from the InspectorA Unity window that displays information about the currently selected GameObject, asset or project settings, allowing you to inspect and edit the values. More info
See in Glossary
. For more information and an example, refer to Support for runtime UI and Create a list view runtime UI.

Additional resources

Load UXML and USS in C# scripts
Find visual elements with UQuery