简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM