如何更改 Unity 图像组件的源图像?

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

我不知道如何更改用于源图像的 sprite。

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;
    }
}

当我输入它时 returns: Assets\Scripts\SceneButton.cs(13,31):错误 CS1061:'Image' 不包含 'sprite' 的定义并且没有可访问的扩展方法 'sprite' 接受类型为 [= 的第一个参数17=] 可以找到(您是否缺少 using 指令或程序集引用?)

我看到很多帖子有人在图像组件上使用 .sprite,所以我不确定为什么我不能

我认为你应该添加 using UnityEngine.UI;命名空间。如果它不起作用,那么尝试像这样创建一个 public 函数:-

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;
}

并在unity的onclick中调用 希望对你有用