Instantiate UXML from C# scripts
Learn how to instantiate UXML with C# by an example.
Read time 1 minuteLast updated 21 days ago
To build UI from a UXML file:
-
Use either:
- to instantiate without a parent, which creates a new
Instantiate().TemplateContainer - to clone inside a parent.
CloneTree(parent)
Once the UXML is instantiated, you can retrieve specific elements from the visual tree 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 references in your MonoBehaviour scripts and assign the UXML assets from the Inspector. For more information and an example, refer to Support for runtime UI and Create a list view runtime UI.
VisualTreeAsset