1
\$\begingroup\$

I'm digging into Unity's new UI Toolkit, and so far I like it a lot; but there are a few things bugging me about it.

I have a dynamic list in my UI which keeps track of way point paths, and it changes its contents with play. This is mostly taken care of with a group and labels added to it in C#; but there's a specific kind of formatting I use for my labels and it's a lot of get/set calls to update it every single time.

Under ideal circumstances, I would make my ideal label in the editor, make it a prefab, and just insert that prefab; but this doesn't seem to be possible with the UI Toolkit.

If I can't make a UI prefab, how can I easily and clearly create the same style of label every single time without too many lines of code?

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Got it.

While UXML (XML in general really) does not qualify as a prefab or typical asset, a utility exists to load such a file as one.

Suppose our file is called "PathLabel", and is in a Resources directory. We can load that utility class like so:

var pathLabelPrefab = Resources.Load<VisualTreeAsset>("PathLabel").CloneTree();

VisualAssetTree qualifies as a loadable asset, and its function, CloneTree(), returns a UITemplates.TemplateContainer. This class is a subclass of VisualElement, and can be added to our UI Document with a simple add call.

Just in case anyone else is curious. In summary, create a new document, drop it in a folder titled "Resources", load it with Resources.Load, and add it to your visual group in your main UI.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ I'd recommend using direct asset references or addressables over Resources.Load. \$\endgroup\$
    – DMGregory
    Nov 16, 2022 at 18:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .