How to bind code to runtime UI?

I’ve recently started using UI Toolkit, and some aspects like styling and layout seem vastly superior to the old way of doing UI in Unity. However I am really struggling to understand how I am meant to structure my code an UI assets.

I’ve followed the guide in the documentation: Unity - Manual: Create a list view runtime UI. The pattern this uses is to create the UI in the UI Builder, then create “controller” classes for each UI element that needs logic.

Firstly, this leads to excessive binding like this m_NameLabel = visualElement.Q<Label>("CharacterName"); which is quite ugly syntax and leads to tight coupling between the “view” and “controller”. Assuming the element has a corresponding USS entry, updating the element name means three places need to be updated.

My bigger issue at the moment is that dynamically adding content means I need to create a VisualTreeAsset template (basically a prefab) and pass it into the controller. This isn’t too bad in the guide where the only one asset is needed and it is only being passed to one controller, but the UI I am trying to build will likely need several layers of controllers (e.g. InventoryScreenController → EquipmentTabController → EquipmentListController) which means that to use a VisualTreeAsset I have to pass it through several classes. It seems like this will get messy very quickly.

So far, the cleanest way I have found to build UI is to do it entirely in code, and ignore the UI Builder. However this isn’t a good practice if you are working on a team project with non-programmers.

Sorry for the ramble, but I would appreciate if anyone could give me any pointers on how to handle this.

1 Like

Hello! Currently what you’re doing with the Q<Label> queries is the right way to go. We’ve been discussing best practices in this area and internally working on some patterns we want to encourage users to follow, but nothing is public at this moment.

In the meantime, you can still organize your code so that only the class querying for components is dependent on the names in the UXML, and have the actual logic run separately and using the class that knows the UI to update UI only.

1 Like