Loading UXML from C# at runtime

Apologies if this is a stupid question but I’m trying to work out how to dynamically load UXML assets at runtime. The example here: Unity - Manual: Loading UXML from C#
only covers the editor.

I have tried:

var template = Resources.Load<VisualTreeAsset>("Assets/SubPanel.uxml");

but always get a null object.

Is it possible?

Are your uxml resources placed in the Resources directory?:stuck_out_tongue:

Thanks. I’ve read the docs on Resources.Load and put the uxml into a Resources folder but it didn’t help. I’ve tried every reasonable path combination too.

When you call Resources.Load you have to give it a path that exists inside the Resources folder. If I understand correctly your UXML is directly under Assets, if you move it to Assets/Resources and call Resources.Load<VisualTreeAsset>("SubPanel"); it should work :slight_smile:

2 Likes

A real rookie error there! Unfortunately even after I put it in Assets/Resources it continues to fail. I’m new to Unity so it’s entirely possible I’m doing something else stupid.

@James_SI sorry I made a mistake, you need to call Resources.Load<VisualTreeAsset>("SubPanel"); (remove the .uxml at the end) for the call to work! I’ve updated my original comment to avoid confusion if someone else finds this thread :wink:

4 Likes