简体   繁体   English

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

[英]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?)当我输入它时,它返回: Assets\\Scripts\\SceneButton.cs(13,31): error CS1061: 'Image' does not contain a definition for 'sprite' 并且没有可访问的扩展方法 'sprite' 接受类型的第一个参数可以找到“图像”(您是否缺少 using 指令或程序集引用?)

I have seen many posts where people use .sprite on an image component, so I am not sure why I am not able to我看过很多帖子,人们在图像组件上使用 .sprite,所以我不知道为什么我不能

I think you should add using UnityEngine.UI;我认为你应该添加 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并从 unity 的 onclick 中调用它可能对你有用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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