Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We are updating our Terms of Service for all Unity subscription plans, effective October 13, 2022, to create a more streamlined, user-friendly set of terms. Please review them here:
    Dismiss Notice
  3. Have a look at our Games Focus blog post series which will show what Unity is doing for all game developers – now, next year, and in the future.
    Dismiss Notice
  4. Join us on Thursday, September 29, for a day with Unity's SRP teams here on the forum or on Reddit, and discuss topics around URP, HDRP, and the Scriptable Render Pipeline in general.
    Dismiss Notice

Changing an image texture by code

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

  1. Suduckgames


    Nov 28, 2016
    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");
    3.         StyleBackground background =;
    4.         background.value.texture = module.moduleIcon;
  2. uDamian


    Unity Technologies

    Dec 11, 2017
    This should be enough:
    Code (CSharp):
    1. = 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.