unity ui

Unity4.6 UI按钮绑定事件(四)

 

The events that are supported by the StandaloneInputModule and TouchInputModule are provided by interface and can be implemented on a MonoBehaviour by implementing the interface. If you have a valid EventSystem configured the events will be called at the correct time.

阅读这段Unity3d的官方文档我们会发现Unity4.6 UI,有一种更简单的方式来监听Button按钮的点击,MouseIn鼠标滑入,MouseOut鼠标滑出等事件,那就是我们我们可以通过实现各个事件的接口类来自定义事件。

三、通过MonoBehaviour 来实现事件类接口来实现事件的监听

第一步:通过Hierarchy面板创建button(详细参考Unity4.6 UI按钮绑定事件(一))

第二步:创建一个名为EventHandler的脚本,代码如下


using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class EventHandler : MonoBehaviour, IPointerClickHandler, IPointerEnterHandler, IPointerExitHandler, IPointerDownHandler, IDragHandler
{
public void OnPointerClick(PointerEventData eventData)
{
if (eventData.pointerId == -1)
Debug.Log("Left Mouse Clicked");
if (eventData.pointerId == -2)
Debug.Log("Right Mouse Clicked");
}

public void OnPointerEnter(PointerEventData eventData)
{
Debug.Log("Pointer Enter");
}

public void OnPointerExit(PointerEventData eventData)
{
Debug.Log("Pointer Exit");
}

public void OnPointerDown(PointerEventData eventData)
{
Debug.Log("Pointer Down");
}

public void OnDrag(PointerEventData eventData)
{
Debug.Log("Dragged");
}
}

More

Unity4.6 UI按钮绑定事件(二)

这篇文章我们继续来看一下Unity4.6 UI中第二种将按钮绑定事件的方法

二、通过绑定脚本来绑定事件

首先,第一步,依旧在Hierarchy面板中创建一个Button

More