【UGUI】Unity4.6 UI按钮绑定事件(三)
我们会发现Unity4.6 UI新的UI系统中Button默认只提供了Onclick的调用方法,有时我们不仅仅想监听Button的Click事件,同时还需要监听MouseIn(鼠标进入事件)MouseOut(鼠标滑出事件).
这时我们就需要借助新的UI系统中EventTrigger脚本来实现,下面我们来学习一下,首先我们看一下如何通过EventTrigger来实现按钮点击Click事件.
第一步:通过Hierarchy面板创建button(详细参考Unity4.6 UI按钮绑定事件(一))
第二步:创建一个名为EventHandler的脚本,代码如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
using
UnityEngine;
using
System.Collections;
using
UnityEngine.UI;
using
UnityEngine.EventSystems;
//需要EventTrigger脚本的支援
[RequireComponent( typeof (UnityEngine.EventSystems.EventTrigger))]
public
class
EventHandler : MonoBehaviour
{
//
Use this for initialization
void
Start()
{
Button
btn = this .GetComponent<Button>();
UnityEngine.EventSystems.EventTrigger
trigger = btn.gameObject.GetComponent<UnityEngine.EventSystems.EventTrigger>();
EventTrigger.Entry
entry = new
EventTrigger.Entry();
entry.eventID
= EventTriggerType.PointerClick;
entry.callback
= new
EventTrigger.TriggerEvent();
entry.callback.AddListener(Onclick);
trigger.delegates.Add(entry);
}
private
void
Onclick(BaseEventData pointData)
{
Debug.Log( "Button
Clicked" );
}
}
|
第三步,绑定EventHandler脚本到Button上
然后运行点击按钮就能看到运行的结果了。
如果我们想在Unity4.6 新的UI中实现MouseIn怎么办,很简单我们只需要修改下EventTriggerType.PointerClick事件类型改为EventTriggerType.PointerEnter,同理要监听MouseOut事件只需要修改为EventTriggerType.PointerExit
新的实现代码如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
using
UnityEngine;
using
System.Collections;
using
UnityEngine.UI;
using
UnityEngine.EventSystems;
//需要EventTrigger脚本的支援
[RequireComponent( typeof (UnityEngine.EventSystems.EventTrigger))]
public
class
EventHandler : MonoBehaviour
{
//
Use this for initialization
void
Start()
{
Button
btn = this .GetComponent<Button>();
UnityEngine.EventSystems.EventTrigger
trigger = btn.gameObject.GetComponent<UnityEngine.EventSystems.EventTrigger>();
EventTrigger.Entry
entry = new
EventTrigger.Entry();
//鼠标点击事件
//entry.eventID
= EventTriggerType.PointerClick;
//鼠标滑出事件
//entry.eventID
= EventTriggerType.PointerExit;
//鼠标进入事件
entry.eventID
= EventTriggerType.PointerEnter;
entry.callback
= new
EventTrigger.TriggerEvent();
entry.callback.AddListener(OnMouseEnter);
trigger.delegates.Add(entry);
}
private
void
OnMouseEnter(BaseEventData pointData)
{
Debug.Log( "Button
Enter" );
}
}
|