- Unity 2018 AR与VR开发快速上手
- 吴雁涛
- 1117字
- 2024-10-30 09:07:00
3.7 Unity GUI
Unity GUI提供了常用的UI(即用户界面),包括按钮、文本、文本框、滚动条、下拉框等。依次单击菜单选项“GameObject→UI”,从中选择需要添加的具体UI即可,如图3-41所示。

图3-41
Unity GUI所有对象都需要归集在画布(Canvas)游戏对象下,并且需要一个事件系统(Event System)游戏对象,如图3-42所示。

图3-42
3.7.1 渲染模式
渲染模式(Render Mode)如图3-43所示。

图3-43
1.屏幕空间-覆盖(Screen Space–Overlay)
该模式下,UI会始终出现在3D物体的最前方,如图3-44所示。

图3-44
2.屏幕空间-摄像机(Screen Space–Camera)
该模式下,UI会出现在距离摄像机一定位置的距离上,其中Plane Distance就是UI所在平面距离摄像机的位置,如图3-45所示。

图3-45
3.世界空间(World Space)
该模式下,UI会变成一个场景中的平面对象,如图3-46所示。

图3-46
3.7.2 矩阵变换(Rect Transform)
Unity GUI的游戏对象使用矩阵变换来设置位置,通过锚点(Anchors)属性来定位一个位置,可以是点、线或者面。根据锚点定位的位置来定位游戏对象的位置,如图3-47所示。

图3-47
Unity提供了一些预设的常用锚点,方便使用者使用,如图3-48所示。

图3-48
1.绝对定位
以父游戏对象的某个点作为锚点时,子游戏对象不会因为父游戏对象的大小变化而跟着改变,会始终保持大小不变,但是界面的UI元素可能会因为屏幕大小的变化跑到屏幕显示区域以外,如图3-49所示。

图3-49
2.相对定位
以父游戏对象的某条线或区块为锚点时,子游戏对象会因为父游戏对象的大小变化而跟着改变,因此界面的UI元素不会因为屏幕大小的变化而跑到屏幕显示区域以外,如图3-50所示。

图3-50
3.7.3 响应脚本
Unity GUI响应UI事件的脚本有两种主要的方式:一种是结合Unity编辑器设置的脚本;另一种是完全在脚本中响应。
两种方法各有利弊:结合Unity编辑器设置的脚本代码简单,耦合低,可以方便地复用,但是脚本多的时候相互之间的逻辑不易看出来;完全在脚本中设置的话,代码略显复杂,但是可以统一管理逻辑。
1.结合Unity编辑器设置的脚本
新建一个脚本,拖到一个空的游戏对象下,如图3-51所示。

图3-51
脚本中需要一个公有的方法,内容如下:

以按钮为例,选中“Button”游戏对象,单击“On Click”标签下的“+”按钮,将包含脚本的游戏对象“GameMaster”拖到其中,在下拉列表中设置响应单击事件的方法是“GUIController”脚本的“OnClicked”方法,如图3-52所示。

图3-52
运行以后,单击按钮就能在控制台窗口看到提示信息,如图3-53所示。

图3-53
这种方法还可以传参数,Unity简单的基本类都可以当作参数。
在脚本中添加以下内容:
public void OnClicked(string str){ Debug.Log(str); }
界面设置和之前一样,设置完成之后会多出一行,用于输入参数,如图3-54所示。

图3-54
此时运行效果如图3-55所示,单击后显示参数的内容。

图3-55
2.完全在代码中响应
在脚本中添加如下代码,设置脚本所在的按钮游戏对象之单击响应事件:

只要将脚本拖到按钮游戏对象上成为组件即可,不需要更多设置,如图3-56所示。

图3-56
其他UI设置的方法都是类似的,如图3-57所示。

图3-57