How to set background image from a string?

I have a peculiar case where a background image is in an unaccessable stylesheet and I’d like to re-use this for another element. I tried setting the style.background from script, but it accepts a texture only – is there a way to get the background image another element uses and re-use that, or to create a background element from a string, or to apply a style on-the-fly with the same image url?

The “usual” magic of replicating the CSS chain of elements so the selector directly applies does not work here since the elements used in the selector are too specific.

Can you use the AssetDatabase to load the texture from the string image path?

Not sure, because the path in the uss file is relative to the uss file, and I’d need to somehow figure that out first. Additionally, loading the same texture again doesn’t sound great from a memory perspective (albeit probably neglectable in an editor context).

To rephrase and potentially make it more clear:
“I have a VisualElement that has a background which is applied through a uss file. How can I apply that same background to an entirely different VisualElement?”

Doesnt element.style.background returns the reference to Textured2D that is used for the background image? If so, may be just fetch it and apply for another element?
Why not just use generic stylesheet for the elements that require that background and instead of doing manual bg swap you just add respective class?

Because the background element comes from a different stylesheet that I don’t control (I’m working on a Packman extension and want visual coherence with existing elements). In previous Unity versions I was able to use the right CSS selectors to get the background image onto my custom elements, but in 2020.1+ the CSS selectors became so strict that this isn’t possible anymore.

Usually, you can query the resolvedStyle of an element once it has been evaluated. Since this is not the case right after creation, you might need to wait a frame to get the resolved styles values of the original element to assign them to the other. Problem is, for some reason the backgroundImage was not part of the resolvedStyles. We fixed this for 2020.2 and it should be present in the first 2020.1 patch release.

1 Like

Thanks for clarifying, no wonder I couldn’t find the background in resolvedStyles :slight_smile:

I’m curious to know what changed that made it so difficult to reuse styles. How strict are we talking?