Dynamically Change Visual Element's Background Image in Unity UI Builder

Viewed 1850

I want to add and remove a Visual Element background image from Unity UI Builder using scripting. I know that this line lets you dynamically change the text of a label in UI Builder:

name_of_my_UI_Builder_Label.text = "Change Label To This Text";

Is there something similar I can do to access my background image here?

3 Answers
name_of_my_UI_Builder_Label.style.backgroundImage = new StyleBackground(sprite);

visualTree.Q("TARGET_ELEMENT").style.backgroundImage = sprite;

The easiest method to do this is,

  • Create an image component.

  • Add a script in which you can add the sprites that you wish to display as a background.

     `public Sprite[] sprites;
      public int loadIndex
      private Image image;
    
      private void Start()
      {
       image = GetComponent<Image>();
       image.sprite = sprites[loadIndex];  
      }
    
Related