为了实现鼠标放置到技能按钮处显示该技能描述的效果,参考了许多资料,由于我是初学者,研究了许久才看明白,现在分享一下学习心得。
效果展示图
代码如下
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class SkillDataDisplay : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IPointerDownHandler
{
//1.1.显示技能描述的组件
public GameObject skilDisplayer;
public Text skilDisplayerText;
public string skillText;
public void OnPointerEnter(PointerEventData eventData)//3.1.监听鼠标进入
{
skilDisplayer.SetActive(true);
skilDisplayerText.text = skillText;
float X = Input.mousePosition.x - Screen.width / 2f + 50f;
if (X > 400) X = 400;
float Y = Input.mousePosition.y - Screen.height / 2f - 50f;
if (Y < -300) Y = -300;
skilDisplayer.transform.localPosition = new Vector2(X, Y);
}
public void OnPointerExit(PointerEventData eventData)//3.2.监听鼠标离开
{
skilDisplayer.SetActive(false);
}
public void OnPointerDown(PointerEventData eventData)//3.3.监听鼠标点击
{
skilDisplayer.SetActive(false);
}
}
1、首先把该脚本放到需要此效果的UI上
2、每有一种需要实现的效果就要在MonoBehaviour后面引入对应的接口,比如:IPointerEnterHandler, IPointerExitHandler, IPointerDownHandler
3、每个接口都必须实现(使用),比如:
方法-public void OnPointerExit(PointerEventData eventData)
{ skilDisplayer.SetActive(false); }-实现IPointerExitHandler接口
4、实现接口必须用public(不知道为什么,反正不用会报错)
5、其他接口与对应的实现方法如下
效果 | 接口名 | 方法名 |
指针(鼠标)进入对象物体范围时 | IPointerEnterHandler | public void OnPointerEnter(PointerEventData eventData){} |
指针离开对象物体范围时 | IPointerExitHandler | public void OnPointerExit(PointerEventData eventData){} |
指针在对象上按下时调用(仅在按下的那一帧) | IPointerDownHandler | public void OnPointerDown(PointerEventData eventData){} |
指针在对象上释放(松开鼠标)时调用(在最初按下的对象上调用) 指针在对象上按住不松手,此时指针离开对象物体范围时也会触发 | IPointerUpHandler | public void OnPointerUp(PointerEventData eventData){} |
指针在同一对象上按下并释放时调用(模拟点击) 指针按下后离开对象物体范围后释放,不触发 | IPointerClickHandler | public void OnPointerClick(PointerEventData eventData){} |
拖拽即将开始时在拖拽对象上调用 | IBeginDragHandler | public void OnBeginDrag(PointerEventData eventData){} |
拖拽发生时在拖拽对象上调用 | IDragHandler | public void OnDrag(PointerEventData eventData){} |
拖拽结束时在拖拽对象上调用 | IEndDragHandler | public void OnEndDrag(PointerEventData eventData){} |
当拖拽结束时在放置目标对象上调用 | IDropHandler | public void OnDrop(PointerEventData eventData){} |
鼠标滚轮滚动时调用 | IScrollHandler | public void OnScroll(PointerEventData eventData){} |
参考原文:
unity的UI内置接口(IBeginDragHandler,IPointerEnterHandler.......)_unity ipointerenterhandler-CSDN博客
标签:鼠标,--,void,public,PointerEventData,对象,eventData,白版,技能 From: https://blog.csdn.net/m0_74463266/article/details/142848951