Changing USS properties from the code (runtime UI)

Hello!
I have a VisualElement with a background image and a c# script that checks some game logic and based on that it is enabling/disabling classes for it. I have also prepared classes with different background images.

My problem is that this is not very scalable, I do not want to have class for every option for backroung image :slight_smile:
I would like to be able to change the one USS property directly from the code, basically do something like (made up example):

 root.Q<VisualElement>("Photo").BackgroundImage =  Resources.Load<Texture>("/Assets/UI/TaskIcons/2.png");

But I know it is not possible. I found out I can manipulate the styleSheets object from the code and I can add a new styleSeet to it, but I did not find how to just change a single property.

Basically what am I looking for is a way how to dynamically change images, the same way as it is for example with the labels (this example works):

root.Q<Label>("WorkerName").text = entity.name;

I am using UI Toolkit 1.0.0. Preview 8 and UI Builder 1.0.0. Preview 6.
Also I am not sure if I should not use the Image (Unity - Scripting API: Image) element, but there is nothing like that in my Library in UI Builder:


Thanks!

1 Like

Hello,

This is actually possible. You just need to use the โ€œstyleโ€ property of VisualElement:

 root.Q<VisualElement>("Photo").style.backgroundImage =  Resources.Load<Texture>("/Assets/UI/TaskIcons/2.png");
3 Likes

Hello! OMG how could I miss that? Thanks a lot, you saved me! :))
Do you also know why I do not have the Image element in the Library?