Runtime Loading UXML in Custom Visual Element

As Hello,

I was an early adopter of UITK, back when it was called UI Elements (or something), when it only supported Editor UI.

I am revisiting it now, in the context of Runtime UI, of which I am really excited about.

I am somewhat surprised on my return that if you have your own Custom Visual Element, if you want to add a predefined UXML to it you need to either:

  • Dynamically load it in with [Resources/Addressables].Load(path)

  • Serialize a VisualTreeAsset on an UnityObject (i.e. not the VisualElement)

I understand your documentations have assets being loading in the ctor of the custom VisualElement. When does that mean the ctor run? When you show the element on screen? that doesn’t sound great, typically you want things loaded before using them.

The above means you need to have something which holds all the references to that VisualTreeAsset. And scaling that up to a full game gives me flashbacks of other systems which have worked like that, they do not scale very well. Nobody wants to search a list of hundreds of VisualTreeAssets to point one elsewhere.

Back in the days of Editor UITK, this was less of an issue.

you use to be able to define the default variable on your EditorWindow script import settings.

As a side note here: I believe I am correct in saying; if you use the TemplateContainer in your UXML this will simply do Resources.Load, there is no Addressables implementation?

Am I missing something, is there a better way to load Visual Tree Assets from a VisualElement at runtime?

I guess its tricky because you have a script which has a dependency on an Asset.

Thanks in advance

Hello,

In terms of how you can reference UXML assets from code, you are not missing anything. It’s a difficult endeavour for the reasons you have mentioned.

The possibilities on how to approach this are covered in the Manual: Encapsulate UXML documents with logic

My main advice would be:

  • For small, highly frequent custom visual elements, it’s actually OK to fallback to code to build the hierarchy since it’s usually small and highly dependent on the behaviour established in C#
  • For more complex hierarchies, consider taking the “UXML-first” approach to benefit from having the UI layout described in UXML
1 Like