一.工作原理
1.在继承MonoBehaviour的脚本中的特殊函数里
2.调用GUI提供的方法
3.类似生命周期函数Unity
注意:
1.它每帧执行相当于是用于专门绘制GUI界面的函数
2.一般只在其中执行GUI相关界面绘制和操作逻辑
3.该函数在onDisable之前 LateUpdate之后执行
4.只要是继承Mono的脚本都可以在onGUI中绘制GUI
二.文本控件和按钮控件
1.文本控件
- 位置参数:Rect参数x y位置w h尺寸
- 显示文本:string参数
- 图片信息:Texture参数
- 综合信息:GUIcontent参数
- 自定义样式:GUIstyle参数
1.必备的参数内容是位置信息和显示信息
2.原点是屏幕左上
public class Lable : MonoBehaviour
{
public Texture texture;
public Rect rect;
public Rect rect1;
public GUIContent uIContent;
public GUIStyle style;
private void OnGUI()
{
//普通显示
GUI.Label(new Rect(0, 0, 100, 40),"Hello World",style);
GUI.Label(rect, texture,style);
//综合信息
GUI.Label(rect1, uIContent,style);
if(uIContent.tooltip != null)
Debug.Log(uIContent.tooltip);
}
}
3.GUIstyle内容
2.按钮控件
类似文本控件
1.返回一个bool值,如果为ture,则按钮被点击
private void OnGUI()
{
if (GUI.Button(rect, uIContent, style))
{
Debug.Log(uIContent.tooltip);
}
}
2.RepeateButton长按按钮,按下就返回,Button只能检测一次点击
3.单选框
private void OnGUI()
{
val = GUI.Toggle(rect,val, uIContent,style);
}
1.修改固定宽高fixedwidth和fixedHeight
2.修改从GUIStyle边缘到内容起始处的空间padding
4.多选框
单选框由多选框实现
public int index = 1;
private void OnGUI()
{
//val = GUI.Toggle(rect,val, uIContent,style);
if(GUI.Toggle(new Rect(0,0,100,40), index==1 , "选项1"))
{
index = 1;
}
if (GUI.Toggle(new Rect(0, 50, 100, 40), index == 2, "选项2"))
{
index = 2;
}
if (GUI.Toggle(new Rect(0, 100, 100, 40), index == 3, "选项3"))
{
index = 3;
}
}
5.输入框
private void OnGUI()
{
#region 普通输入
inputStr = GUI.TextField(new Rect(0,0,100,40), inputStr);
#endregion
#region 密码输入
passStr = GUI.PasswordField(new Rect(0, 40, 100, 40), passStr,'*');
#endregion
}
6.拖动框
public float val=0.5f;
public float min=0;
public float max=1;
private void OnGUI()
{
#region 水平拖动条
val = GUI.HorizontalSlider(new Rect(0, 80, 100, 40), val, min, max);
#endregion
#region 垂直拖动条
val = GUI.VerticalSlider(new Rect(0, 120, 100, 40), val, min, max);
#endregion
}