【问题标题】:Change Source Image of a UI Button when a mouse is over it? (Unity)鼠标悬停时更改 UI 按钮的源图像? (统一)
【发布时间】:2017-12-18 19:17:48
【问题描述】:

您好,我是 Unity 新手,我正在尝试让 UI 按钮在鼠标悬停时更改其源图像,当鼠标不再悬停在按钮上时,按钮的源图像恢复正常.我知道需要一个精灵作为按钮的源图像,所以我创建了两个图像精灵文件(一个是普通图像,另一个是鼠标悬停在按钮上时亮起的图像)

现在这里是播放按钮的屏幕截图,具有正常的源图像

当鼠标移过按钮时,按钮会通过点亮来改变它的源图像

如何在 C# 中执行此任务?当鼠标悬停在 C# 中,如何更改按钮的源图像?

这是我在查看了一些参考资料后得到的。我是 Unity 新手,很抱歉我缺乏知识

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class PlayButton : MonoBehaviour {

    private PlayButton pb;
    private Sprite newSprite;

    // Use this for initialization
    void Start () {
        pb = GetComponentInChildren<PlayButton> ();
    }

    // Update is called once per frame
    void Update () {

    }

    public void onClick(){

    }

    public void onPointerHover(PointerEventData eventData){
        //When mouse hovers over the button, the button changes
        pb.image.overrideSprite = newSprite;
    }
 }

【问题讨论】:

  • 按钮默认行为在突出显示时已经点亮了图像。

标签: c# user-interface button unity3d unity3d-2dtools


【解决方案1】:

没有onPointerHover 这样的东西。检测鼠标悬停使用OnPointerEnter。要从鼠标上方检测鼠标何时存在,请使用OnPointerExit。您必须实现IPointerExitHandlerIPointerEnterHandler 才能使用这些功能。

您阅读了更多示例here

至于更改Button的源图片,Button.image.spriteButton.image.overrideSprite可以做到。

只需附加这个按钮对象:

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class PlayButton : MonoBehaviour, IPointerExitHandler, IPointerEnterHandler
{
    private Button pb;
    public Sprite newSprite;

    void Start()
    {
        pb = GetComponent<Button>();
    }

    public void OnPointerEnter(PointerEventData eventData)
    {
        pb.image.sprite = newSprite; ;
        Debug.Log("Mouse Enter");
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        Debug.Log("Mouse Exit");
        //Change Image back to default?
    }
}

编辑

请注意,您不必自己执行此操作。 Unity 已经内置了这样做的方法。

1.将按钮的转换选项从“Color Tint”更改为“Sprite Swap”

2.将“Highlighted Sprite”槽更改为您想要的任何Sprite。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-10
    • 2010-11-30
    相关资源
    最近更新 更多