Changing image via script doesn't work

Hello,

I’d like to change Image property image with a different texture during runtime. I’ve tried this on empty project, but nothing happens after code is executed.

using UnityEngine.UIElements;
// ********************************
    [SerializeField]
    private GameObject image;
    [SerializeField]
    private Texture swordImage;

    void Start()
    {
        Image img = image.GetComponent<Image>();
        img.image = swordImage;
    }

This script is applied to GameManager, that has reference to texture of a sword and Image component on canvas. I’ve checked documentation many times, and it says there is a property Image.image that has type Texture. Earlier versions of unity were using Image.sprite property, but it was deleted in new Unity version.
6732307--775003--upload_2021-1-16_21-40-38.png
6732307--775012--upload_2021-1-16_21-41-7.png

Any help is apprecieated

6732307--775003--upload_2021-1-16_21-40-38.png

I’ve tried to change the type of image variable to Image or even VisualElement, but they are not showing in the Unity editor to drag-and-drop on them.

When you add an Image to a Canvas, traditionally it comes from the UnityEngine.UI namespace.

You’re including the UnityEngine.UIElements namespace, which I have not used.

The image from UnityEngine.UIElements.Image is a completely different animal about which I know nothing.

UnityEngine.UI.Image still uses the .sprite property, not a Texture.

Sorry, but UnityEngine.UI namespace is not avaible in Unity 2019.3 that I am using.

It’s a package on the package manager.

You are right! My visual studio was babling that this namespace does not exists.

1 Like