首页 > 代码库 > ngui 输入事件处理

ngui 输入事件处理

NGUI不仅提供了图形接口,还提供了输入事件接口!事件接口是通过UICamera来实现的。


Unity3d 为我们提供的原装的input尽管非常方便,但真正跨平台使用时(尤其是跨手机与Pc机时)仍然不是非常方便。


NGUI对input又进行了二次封装,将全部平台上的事件统一转换成MouseOrTouch。

使用起来也比input要方便的多。input要在update中处理。而NGUI为我们提供了大量的函数,若要使用函数。仅仅须要在脚本中加入下列函数就可以:

/// - OnHover (isOver) is sent when the mouse hovers over a collider or moves away.
/// - OnPress (isDown) is sent when a mouse button gets pressed on the collider.
/// - OnSelect (selected) is sent when a mouse button is released on the same object as it was pressed on.
/// - OnClick () is sent with the same conditions as OnSelect, with the added check to see if the mouse has not moved much. UICamera.currentTouchID tells you which button was clicked.
/// - OnDoubleClick () is sent when the click happens twice within a fourth of a second. UICamera.currentTouchID tells you which button was clicked.
/// - OnDrag (delta) is sent when a mouse or touch gets pressed on a collider and starts dragging it.
/// - OnDrop (gameObject) is sent when the mouse or touch get released on a different collider than the one that was being dragged.
/// - OnInput (text) is sent when typing (after selecting a collider by clicking on it).
/// - OnTooltip (show) is sent when the mouse hovers over a collider for some time without moving.
/// - OnScroll (float delta) is sent out when the mouse scroll wheel is moved.
/// - OnKey (KeyCode key) is sent when keyboard or controller input is used.


但它的缺点就是。这些事件都要基于碰撞体。也就是说,若要使用这些函数,就必须将脚本所在的gameobject上加入碰撞体。!!

这样。假设出现多层叠加的情况,就比較纠结了。

比方如今有这样一个需求:

1、有一个面板,这个面板支持左右拖动。而且在此面包上的不论什么地方拖动都有效!

2、此面板上有个button。

3、当在button上左右拖拽时,面板也要感应到拖拽事件!

若要完毕这个需求,首先须要有两个碰撞体,非常明显,button的碰撞体要在面板的上面。但这样无法完毕第三条需求。


幸运的是,NGUI为我们留了个后门!它能够设置一个默认的事件接受体。

切此gameobjec不须要碰撞体!

static public GameObject genericEventHandler;
如今实现上面提到的三个需求。

1、将面板的gameobject赋值给genericEventHandler。

2、给面板上的某个脚本加入一个OnDrag函数

3、加入一个button(有碰撞体)

这样就攻克了上面的问题,且仅仅须要一个碰撞体!


ngui 输入事件处理