UGUI的事件系统默认使用时,是需要当前的类继承事件接口,就可以在该类中加入它的事件方法,但是在多人开发时这种方式没什么好处。
用过NGUI的或许都知道UIEventListener这个类,因为使用超级方便,直接加入UI对象进行事件注册即可。其实UGUI也可以模仿这种方式进行封装。
代码如下:
- usingUnityEngine;
- usingSystem.Collections;
- usingUnityEngine.EventSystems;
-
publicclassUUIEventListener
: MonoBehaviour, - IPointerClickHandler,
- IPointerDownHandler,
- IPointerEnterHandler,
- IPointerExitHandler,
- IPointerUpHandler,
- ISelectHandler,
- IUpdateSelectedHandler,
- IDeselectHandler,
- IDragHandler,
- IEndDragHandler,
- IDropHandler,
- IScrollHandler,
- IMoveHandler
- {
-
publicdelegate
voidVoidDelegate(GameObject
go); -
publicVoidDelegate
onClick; -
publicVoidDelegate
onDown; -
publicVoidDelegate
onEnter; -
publicVoidDelegate
onExit; -
publicVoidDelegate
onUp; -
publicVoidDelegate
onSelect; -
publicVoidDelegate
onUpdateSelect; -
publicVoidDelegate
onDeSelect; -
publicVoidDelegate
onDrag; -
publicVoidDelegate
onDragEnd; -
publicVoidDelegate
onDrop; -
publicVoidDelegate
onScroll; -
publicVoidDelegate
onMove; -
publicobject
parameter; -
publicvoidOnPointerClick(PointerEventData
eventData) { if(onClick
!= null)onClick(gameObject);
} -
publicvoidOnPointerDown(PointerEventData
eventData) { if(onDown
!= null)onDown(gameObject);
} -
publicvoidOnPointerEnter(PointerEventData
eventData) { if(onEnter
!= null)onEnter(gameObject);
} -
publicvoidOnPointerExit(PointerEventData
eventData) { if(onExit
!= null)onExit(gameObject);
} -
publicvoidOnPointerUp(PointerEventData
eventData) { if(onUp
!= null)onUp(gameObject);
} -
publicvoidOnSelect(BaseEventData
eventData) { if(onSelect
!= null)onSelect(gameObject);
} -
publicvoidOnUpdateSelected(BaseEventData
eventData) { if(onUpdateSelect
!= null)onUpdateSelect(gameObject);
} -
publicvoidOnDeselect(BaseEventData
eventData) { if(onDeSelect
!= null)onDeSelect(gameObject);
} -
publicvoidOnDrag(PointerEventData
eventData) { if(onDrag
!= null)onDrag(gameObject);
} -
publicvoidOnEndDrag(PointerEventData
eventData) { if(onDragEnd
!= null)onDragEnd(gameObject);
} -
publicvoidOnDrop(PointerEventData
eventData) { if(onDrop
!= null)onDrop(gameObject);
} -
publicvoidOnScroll(PointerEventData
eventData) { if(onScroll
!= null)onScroll(gameObject);
} -
publicvoidOnMove(AxisEventData
eventData) { if(onMove
!= null)onMove(gameObject);
} -
staticpublicUUIEventListener
Get(GameObject go) - {
- UUIEventListenerlistener
= go.GetComponent(); -
if(listener
== null)listener
= go.AddComponent(); - returnlistener;
- }
- }
使用方式:
- UUIEventListener.Get(btn.gameObject).onClick=
OnClickBtn; - UUIEventListener.Get(btn.gameObject).parameter=
index; -
privatevoidOnClickBtn(GameObject
go) - {
-
intindex
= (int)UUIEventListener.Get(go).parameter; - Debug.Log("您单击的索引为:"+
index); - }