How do I update an image on a visual element at runtime in ui toolkit?


I’ve been following the UI Toolkit runtime UI tutorial in the docs here.

I have performed all the steps given in the tutorials and it seems to work ok, the only issue I’m having is when trying to update the image when changing the selected character, this is throwing a NullReferenceException:

NullReferenceException: Object reference not set to an instance of an object CharacterListController.OnCharacterSelected (System.Collections.Generic.IEnumerable1[T] selectedItems) (at Assets/Scripts/UI/CharacterListController.cs:106)`

The line in question is this: = new StyleBackground(selectedCharacter.m_PortraitImage);

I spun up a debugger to see what was going wrong and it appears that something breaks when converting the sprite I’ve added (selectedChars.m_PotraitImage) to the backgroundImage. The sprite is valid at this point (not null anyway). The sprite itself is just a jpg image, although I’ve tried it with a png image as well without success.

I’ve double-checked that the code I’ve got is the same as that stated in the tutorial, which it is. I’ve also manually assigned a static image to the visual element which seems to work fine (this is not a solution I can use as I need the images to be dynamically updated).

My question is, what’s going wrong here? Is this the correct way to set images in UIToolkit/UIBuilder?

Any help would be much appreciated,


(Full stack trace attached):

After more experimentation, there seems to be an issue with creating the background style on the fly.

I split the creation of the background style onto its own line then assigned the new style and it seemed to work ok:

var backgroundImage = new StyleBackground(selectedCharacter.m_PotratImage); = backgroundImage;

Still not convinced this is the underlying issue, but at least I’m moving again now.