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、此面板上有个按钮,

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

若要完成这个需求,首先需要有两个碰撞体,很明显,按钮的碰撞体要在面板的上面!但这样无法完成第三条需求!


幸运的是,NGUI为我们留了个后门!它可以设置一个默认的事件接受体。切此gameobjec不需要碰撞体!

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

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

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

3、添加一个按钮(有碰撞体)

这样就解决了上面的问题,且只需要一个碰撞体!


你可能感兴趣的:(NGUI,输入事件,多碰撞体)