Jaedon KLB
Jaedon KLB

Reputation: 99

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

Upvotes: 6

Views: 27333

Answers (3)

okMizu
okMizu

Reputation: 1

I ran into this exact problem right now, it was my fault since I didn't bother to read the Resources.Load documentation first:

"Loads the asset of the requested type stored at path in a Resources folder."

Your sprites have to be in a Folder called Resources, in my case all my sprites were in a folder called "Images", I renamed it to "Resources" instead and it worked like intended.

Upvotes: 0

Jakob Pressley
Jakob Pressley

Reputation: 23

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.

Upvotes: 0

I-am-developer-9
I-am-developer-9

Reputation: 494

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

Upvotes: 5

Related Questions