UguiEventListener

思考并回答以下问题:

  • 这个类干嘛用的?
  • 如何监测UI图片Image的单击事件?
  • Unity开发有一个重要的原则是不要手动拖代码,一切拖动的都需要优化成自动加载,怎么理解?
  • 为什么静态成员只能访问静态成员?

UI的Image不像Button,没有一开始自带了单击事件。如果需要给Image添加单击事件,需要这样做:

1
2


修改后,无需手动给Image添加脚本,直接寻找到Image,因为脚本不是挂载到Image上,所以新增了委托机制,用于在另外的脚本处(没有挂载到Image上)定义单击后要处理的事情。

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;

public class UguiEventListener : UnityEngine.EventSystems.EventTrigger
{
// EventTrigger是Unity里面自带的类,主要用来监测UI的单击、拖拽等行为
public delegate void VoidDelegate(GameObject go);
public VoidDelegate onClick;
public VoidDelegate onDown;
public VoidDelegate onEnter;
public VoidDelegate onExit;
public VoidDelegate onUp;
public VoidDelegate onSelect;
public VoidDelegate onUpdateSelect;


public static UguiEventListener Get(GameObject go)
{
UguiEventListener listener = go.GetComponent<UguiEventListener>();
if (listener == null)
{
listener = go.AddComponent<UguiEventListener>();
}
return listener;
}


public override void OnPointerClick(PointerEventData eventData)
{
if (onClick != null) onClick(this.gameObject);
}


public override void OnPointerDown(PointerEventData eventData)
{
if (onDown != null) onDown(gameObject);
}


public override void OnPointerEnter(PointerEventData eventData)
{
if (onEnter != null) onEnter(gameObject);
}

public override void OnPointerExit(PointerEventData eventData)
{
if (onExit != null) onExit(gameObject);
}

public override void OnPointerUp(PointerEventData eventData)
{
if (onUp != null) onUp(gameObject);
}

public override void OnSelect(BaseEventData eventData)
{
if (onSelect != null) onSelect(gameObject);
}

public override void OnUpdateSelected(BaseEventData eventData)
{
if (onUpdateSelect != null) onUpdateSelect(gameObject);
}
}

使用

无需再给Image手动添加脚本,

1
2
3
4
5
6
7
8
9
10
11
public class MainUI : BaseUI
{
private Transform image;

UguiEventListener.Get(image.gameObject).onClick = Show;

private void Show(GameObject go)
{
Debug.Log("***");
}
}

调用的onClick是个委托,真正的单击监听是OnPointerClick,因为UguiEventListener脚本自动挂载到了Image上。

0%