Changing image on button - image.sprite not working

it seems image.sprite is not present in unity 2020. How can I change the actual graphic via c# code?

   Image t0 = myButtons[0].GetComponent<Image>();
   t0.sprite = theSprite; //<--- doesn't work:'cannot resolve symbol sprite'

Thanks.

Make sure you have installed and used NOT the UIElements namespace but instead the UnityEngine.UI namespace.

How to understand compiler and other errors and even fix them yourself:

https://discussions.unity.com/t/824586/8

If you post a code snippet, ALWAYS USE CODE TAGS:

How to use code tags: https://discussions.unity.com/t/481379

How to report your problem productively in the Unity3D forums:

http://plbm.com/?p=220

1 Like

Thank you very much, will edit original question for code formating.

Itā€™s Image.image, not .sprite. Texture should be a Sprite (2D and UI) texture type though.

Actually seejay, I donā€™t think he wants that one, but I could be wrong. I think he wants the UnityEngine.UI stuff, not the UIElements stuff, and I base that just on him talking about buttons, which usually means in the UI stuff.

Oh, thatā€™s right, itā€™s the image inside the button. I read it too fast :wink:

This works. I think the OP had an issue with theSprite, not with the implementation. Needs to be a sprite-based texture.

using UnityEngine;
using UnityEngine.UI;

public class buttonTestScript : MonoBehaviour
{
    Image myButtonImage;
    public Sprite myButtonSprite;

    void Start()
    {
        myButtonImage = GetComponent<Image>();
        myButtonImage.color = new Color(1, 0, 0, 1); // because you can
        myButtonImage.sprite = myButtonSprite;
    }

}
1 Like

Hi, I was missing the correct reference indeed, as posted by Kurt-Dekker. Donā€™t see a ā€œsolvedā€ button, but itā€™s now.

Thanks a lot for your help.