Unity 怎么像OnClick()一样添加更多其他点击事件

时间:2022-12-29 09:06:28

Hello ,I am KitStar



        Unity自身的Button组件可以绑定的时间状态有限。只有OnClick()。(我目前还不知道有没有其他点击状态可以简单的绑定,各位客官有的话及时给我说。)
        所以自己通过几行的代码。添加更多的点击状态。想要更多丰富的功能的话。只要在对应的方法里面添加即可。


  1. 比较简单了,是个基本的父类。就几段,所以老规矩上脚本吧。

public abstract class UIEventManagers : MonoBehaviour ,IPointerClickHandler,IPointerDownHandler,IPointerEnterHandler,IPointerExitHandler,IPointerUpHandler{

public UnityEvent onPointerDown;
public UnityEvent onPointerUp;
public UnityEvent onPointerEnter;
public UnityEvent onPointerClick;
public UnityEvent onPointerExit;
/// <summary>
/// 鼠标点击
/// </summary>
/// <param name="eventData"></param>
protected virtual void OnPointerClick(PointerEventData eventData)
{
onPointerClick.Invoke();
}

/// <summary>
/// 鼠标退出
/// </summary>
/// <param name="eventData"></param>
protected virtual void OnPointerExit(PointerEventData eventData)
{
onPointerExit.Invoke();
}
/// <summary>
/// 鼠标进入
/// </summary>
/// <param name="eventData"></param>
protected virtual void OnPointerEnter(PointerEventData eventData)
{
onPointerEnter.Invoke();
}
/// <summary>
/// 鼠标按下
/// </summary>
/// <param name="eventData"></param>
protected virtual void OnPointerUp(PointerEventData eventData)
{
onPointerUp.Invoke();
}
/// <summary>
/// 鼠标抬起
/// </summary>
/// <param name="eventData"></param>
protected virtual void OnPointerDown(PointerEventData eventData)
{
onPointerDown.Invoke();
}


# region .
void IPointerClickHandler.OnPointerClick(PointerEventData eventData)
{
OnPointerClick(eventData);
}

void IPointerDownHandler.OnPointerDown(PointerEventData eventData)
{
OnPointerDown(eventData);
}

void IPointerEnterHandler.OnPointerEnter(PointerEventData eventData)
{
OnPointerEnter(eventData);
}

void IPointerExitHandler.OnPointerExit(PointerEventData eventData)
{
OnPointerExit(eventData);
}

void IPointerUpHandler.OnPointerUp(PointerEventData eventData)
{
OnPointerUp(eventData);
}
#endregion .
}

2. 再写一些脚本。继承这个,然后丰富自己的功能吧