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 have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice
  4. Dismiss Notice

Question Using the <Image> element to display sprites

Discussion in 'UI Toolkit' started by tobihoffmann, Jun 9, 2021.

  1. tobihoffmann

    tobihoffmann

    Joined:
    Nov 4, 2019
    Posts:
    6
    I want to dynamicly display images in my UI which are stored in ScritableObjects as sprites.
    But if i set the sprites to the respective <Image> element nothing happens (no error messages as well).
    I do the same with text of <Label> elements and those work fine.

    Code (CSharp):
    1. using System;
    2. using Data.Items;
    3. using UnityEngine;
    4. using UnityEngine.UIElements;
    5.  
    6. namespace UI
    7. {
    8.     public class WeaponEquipment : MonoBehaviour
    9.     {
    10.         private VisualElement _root;
    11.  
    12.         [SerializeField] Weapon weapon;
    13.      
    14.         private Image _rrtIcon;
    15.         private Image _itemView;
    16.  
    17.  
    18.         public void OnEnable()
    19.         {
    20.             // Get the UXML-Tree
    21.             _root = GetComponent<UIDocument>().rootVisualElement;
    22.  
    23.             _rrtIcon = _root.Q<Image>("rrt-icon");
    24.             _itemView = _root.Q<Image>("item-view");
    25.         }
    26.  
    27.  
    28.         // Update is called once per frame
    29.         void Update()
    30.         {
    31.             _rrtIcon.sprite = weapon.rrt;
    32.             _itemView.sprite = weapon.artwork;
    33.         }
    34.     }
    35. }
    36.  
    I am using Unity 2020.3.11f1 with UI Builder 1.0.0-preview.14
     
    Last edited: Jun 9, 2021
  2. tobihoffmann

    tobihoffmann

    Joined:
    Nov 4, 2019
    Posts:
    6
    I am an idiot. Everything works with this code. The problem just was that i'm an idiot.
     
  3. martinpa_unity

    martinpa_unity

    Unity Technologies

    Joined:
    Oct 18, 2017
    Posts:
    364
    It happens to the best of us. Glad it's working for you!