簡體   English   中英

當鼠標懸停在UI按鈕上時更改它的源圖像嗎? (統一)

[英]Change Source Image of a UI Button when a mouse is over it? (Unity)

您好,我是Unity的新手,我試圖使UI按鈕在鼠標懸停在其上方時更改其源圖像,並且當鼠標不再位於該按鈕上方時,該按鈕的Source Image恢復正常。 我知道需要一個精靈作為按鈕的源圖像,所以我創建了兩個圖像精靈文件(一個是普通圖像,另一個是鼠標懸停在按鈕上時的點亮圖像)。

現在這是具有正常源圖像的播放按鈕的屏幕截圖

在此處輸入圖片說明

當鼠標移到按鈕上時,按鈕將通過點亮來更改其源圖像

在此處輸入圖片說明

如何在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;
    }
 }

沒有onPointerHover這樣的東西。 要檢測鼠標懸停,請使用OnPointerEnter 要檢測鼠標從上方移出的時間,請使用OnPointerExit 您必須實現IPointerExitHandlerIPointerEnterHandler才能使用這些功能。

您可以在此處閱讀更多示例。

至於更改Button的源Image,可以使用Button.image.spriteButton.image.overrideSprite來完成。

只需附加這個Button對象:

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。將按鈕的“過渡”選項從“色彩色調”更改為““精靈交換””

2。“突出顯示的精靈”插槽更改為所需的精靈。

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM