Skip to main content
2 of 3
Added reference to unity version + added UI toolkit to title
TheWolfNL
  • 153
  • 1
  • 8

Is it possible to create UI instances of a UI template from code? [Unity UI-toolkit]

Unity UI Toolkit from Unity 2021.2

Looking at the following example:

<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" xsi="http://www.w3.org/2001/XMLSchema-instance" engine="UnityEngine.UIElements" editor="UnityEditor.UIElements" noNamespaceSchemaLocation="../../../UIElementsSchema/UIElements.xsd" editor-extension-mode="False">
  <!-- Creates our template and gives it a name for future reference. -->
  <ui:Template src="Assets/Editor/Resources/ButtonTemplate.uxml" name="button-template" />
  <!-- Creates a parent VisualElement inside which we will use our button template. -->
  <ui:VisualElement class="buttons-container">
    <!-- Instantiates the template multiple times. Each time, we give it a name for future reference. -->
    <ui:Instance template="button-template" name="Cube"/>
    <ui:Instance template="button-template" name="Sphere"/>
    <ui:Instance template="button-template" name="Capsule"/>
    <ui:Instance template="button-template" name="Cylinder"/>
    <ui:Instance template="button-template" name="Plane"/>
  </ui:VisualElement>
</ui:UXML>

The question is if/how one can create those instances of a template from code instead of having to add them manually. The final result i would like to use it on is not a button, but a different template. Another criteria is that it should be buildable while not in editor window, because that is somewhat explained here

TheWolfNL
  • 153
  • 1
  • 8