Search Unity

Changing an image texture by code

Discussion in 'UI Toolkit' started by Suduckgames, Jul 14, 2020.

  1. Suduckgames

    Suduckgames

    Joined:
    Nov 28, 2016
    Posts:
    218
    Hi there I am trying to implement simple functionally but I am unable to make it. I have a list view with some elements and that elements have an image (Since there is no control for images, I have a Visualelement with a background image).

    I will like to change the image texture by code but I am unable to access that property

    I have tried the following code but StyleBackground is not a variable. Any help will be appreciated
    Code (CSharp):
    1.     VisualElement mainImg = adapter.Q<VisualElement>("MainImg");
    2.  
    3.         StyleBackground background = mainImg.style.backgroundImage;
    4.         background.value.texture = module.moduleIcon;
     
  2. uDamian

    uDamian

    Unity Technologies

    Joined:
    Dec 11, 2017
    Posts:
    1,231
    This should be enough:
    Code (CSharp):
    1. mainImg.style.backgroundImage = module.moduleIcon;
    StyleBackground is a struct so if you assign it to a variable (your "background" variable) and then change one of its fields, your mainImg element will not know anything about it. Structs in c# are copied like a value, not referenced.

    Also, when you do
    style.backgroundImage = something
    , there's a custom cast operator= that converts your "something" Texture2D to a StyleBackground. So you don't need to "new StyleBackground()" or anything like that. Same goes for all other style properties.
     
    Suduckgames likes this.