- Unity3D平台AR与VR开发快速上手
- 吴雁涛
- 561字
- 2025-02-26 12:47:23
3.7 Unity GUI
Unity GUI提供了常用的UI,包括按钮、文本、文本框、滚动条、下拉框等。点击菜单“GameObject”→“UI”,选择需要添加的具体内容即可,如图3-38所示。

图3-38
Unity GUI所有对象都需要在“Canvas”为根结点的游戏对象下,并且需要一个“EventSystem”对象,如图3-39所示。

图3-39
3.7.1 Render Mode显示模式
Render Mode显示模式设置界面如图3-40所示。

图3-40
(1)Screen Space - Overlay
该模式下,UI会始终出现在3D物体的最前方,如图3-41所示。

图3-41
(2)Screen Space - Camera
该模式下,UI会出现在距离相机一定位置的距离上,其中“Plane Distance”就是UI所在平面距离相机的位置,如图3-42所示。

图3-42
(3)World Space
该模式下,UI会变成一个场景中的平面对象,如图3-43所示。

图3-43
3.7.2 定位方式
(1)绝对定位
以父对象的某个点作为定位参考时,对象不会因为父对象的大小变化而改变,会始终保持大小不变,如图3-44所示。

图3-44
(2)相对定位
以父对象的某条线或区块为定位参考时,对象会因为父对象的大小变化而改变,如图3-45所示。

图3-45
3.7.3 响应脚本
新建脚本:
using UnityEngine; using System.Collections; public class BtnClicked : MonoBehaviour { public void Clicked(){ Debug.Log ("按钮被按下"); } }
新建一个游戏对象,将脚本拖入,如图3-46所示。

图3-46
选中对应的UI,添加事件,如图3-47、图3-48所示。

图3-47

图3-48
将有脚本的游戏对象拖入事件中,并选择响应的方法,也就是之前写的方法,如图3-49所示。

图3-49
运行,按钮被点击时,就会有输出,如图3-50所示。

图3-50
不同的UI组件只是响应的事件不同,添加响应脚本的方法是一样的,如图3-51所示。

图3-51