Len*_*Ngo 1 c# user-interface button unity-game-engine unity3d-2dtools
您好,我是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;
}
}
Run Code Online (Sandbox Code Playgroud)
没有这样的事情onPointerHover。要检测鼠标过度使用OnPointerEnter。要从上方将鼠标检测到存在,请使用OnPointerExit。您必须实现IPointerExitHandler和IPointerEnterHandler才能使用这些功能。
您可以在此处阅读更多示例。
至于更改按钮的源图像,Button.image.sprite还是Button.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?
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:
请注意,您不必自己执行此操作。Unity已经建立了实现此目的的方法。
1。将按钮的“过渡”选项从“色彩色调”更改为““精灵交换””。
2。将“突出显示的精灵”插槽更改为所需的精灵。
| 归档时间: |
|
| 查看次数: |
3329 次 |
| 最近记录: |