您的位置首页百科问答

Unity 入门教程 物体的OnMouse事件使用

Unity 入门教程 物体的OnMouse事件使用

的有关信息介绍如下:

Unity 入门教程 物体的OnMouse事件使用

Unity 入门教程 物体的OnMouse事件使用。物体的OnMouse事件使用,可以方便处理对3D点击事件,而不是都用射线碰撞的形式,简单的效果和操作如下:

OnMouseDown():OnMouseDown is called when the user has pressed the mouse button while over theGUIElementorCollider.

OnMouseOver():Called every frame while the mouse is over theGUIElementorCollider.A call toOnMouseEnteroccurs on the first frame the mouse is over the object. OnMouseOver is then called each frame until the mouse moves away, at which pointOnMouseExitis called.This function is not called on objects that belong to Ignore Raycast layer.

OnMouseUp():OnMouseUp is called when the user has released the mouse button.

Note that OnMouseUp is called even if the mouse is not over the sameGUIElementorCollideras the has mouse has been pressed down on. For button-like behavior see:OnMouseUpAsButton.

打开Unity,在场景中新建一个 “Cube”,并且和主摄像机“Main Camera”进行调整,使运行场景时能有个好的观察角度,如下图

然后,给“Cube”新建添加个脚本,可以命名为“MouseEvent”,如下图

接着,打开脚本进行代码编辑,这里主要拿“OnMouseUp()”、“OnMouseOver()”和“OnMouseDown()”举例;当鼠标抬起“OnMouseUp()”使物体变红色,当鼠标悬浮在物体上“OnMouseOver()”使物体旋转,当鼠标在物体上按下“OnMouseDown()”使物体变绿色,代码如下图

脚本编译正确后,回到Unity界面,运行场景,如下图

当鼠标悬浮在物体上“OnMouseOver()”使物体旋转,如下图

当鼠标在物体上按下“OnMouseDown()”使物体变绿色,如下图

当鼠标抬起“OnMouseUp()”使物体变红色,如下图

到此,Unity入门教程,物体的OnMouse事件使用讲解结束,更多OnMouse鼠标事件可参见Unity Manual,谢谢