4

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

Jaedon KLB
  • 67
  • 1
  • 1
  • 6
  • Check again, according to the error, the image component of the game object which you're referring to, does not have a sprite. Attach a screenshot of the gameobject components – Anirudh Ganesh Oct 29 '20 at 18:31

2 Answers2

3

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

I-am-developer-9
  • 434
  • 1
  • 5
  • 13
0

Another reason is that Image might be ambiguous, this means you have to set Image to reference an exact namespace as so:

using Image = UnityEngine.UI.Image;

If you don't do this you may get an error stating that it is an ambiguous term. You are going to want to state it along with all of the other namespaces for it to work.