Search code examples
c#unity-uiunity-components

How do I change the source image of a Unity image component?


I can't figure out how to change the sprite used for the source image.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;

public class SceneButton : MonoBehaviour
{
    public Sprite ButtonOff;
    public Sprite ButtonOn;

    private void OnMouseDown()
    {
        gameobject.GetComponent<Image>().sprite = ButtonOn;
    }
}

when I type this out it returns: Assets\Scripts\SceneButton.cs(13,31): error CS1061: 'Image' does not contain a definition for 'sprite' and no accessible extension method 'sprite' accepting a first argument of type 'Image' could be found (are you missing a using directive or an assembly reference?)

I have seen many posts where people use .sprite on an image component, so I am not sure why I am not able to


Solution

  • I think you should add using UnityEngine.UI; namespace. If it not work then try to make a public function as this:-

    public GameObject soundButton;
    public sprite soundOn;
    public sprite soundOff;
    public void ChangeSprite()
    {
        // getting Image component of soundButton and changing it
        soundButton.GetComponent<Image>().sprite = soundOn;
    }
    

    And call it from the onclick of unity May it's work for you