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

2025-10-26 06:51:15

1、OnMouseDown():OnMouseDown is called when the user has pressed the mouse button while over the GUIElement or Collider.

2、OnMouseOver():Called every frame while the mouse is over the GUIElement or Collider.A call to OnMouseEnter occurs on the first frame the mouse is over the object. OnMouseOver is then called each frame until the mouse moves away, at which point OnMouseExit is called.This function is not called on objects that belong to Ignore Raycast layer.

3、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 same GUIElement or Collider as the has mouse has been pressed down on. For button-like behavior see: OnMouseUpAsButton.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢