Adding image in Unity UI toolkit

Hello, I need to add an image to my game UI built with UI toolkit.
I came to know its not directly available by default. From other post I added an image component in my code and added that from project elements to the main panel. But I am unable to set a sprite or source image or background to that image.
How can I assign image? How to add an image?

using UnityEngine.UIElements;

public class MyImage : Image
{
    public new class UxmlFactory : UxmlFactory<MyImage, Image.UxmlTraits>{}

    public MyImage()
    {
       
    }
}

Update: Hey guys, got the fix, its working. I had to set min size. Thanks.

Not sure what’s not working for you.

If you’re using Unity 6 (as you have tagged this thread) then you don’t need to use the old UxmlFactory boilerplate any more.

You can make properties editable in the inspector too:

using UnityEngine;
using UnityEngine.UIElements;

[UxmlElement]
public partial class UXMLImage : Image
{
	#region Constructors
	
	public UXMLImage() : base()
	{
		
	}

	#endregion

	#region Properties

	[UxmlAttribute]
	public new Texture image
	{
		get => base.image;
		set => base.image = value;
	}

	[UxmlAttribute]
	public new Sprite sprite
	{
		get => base.sprite;
		set => base.sprite = value;
	}

	#endregion
}

This works for me:

2 Likes