版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
GUI控件(三)
Button控件
Button控件即为按钮控件,当玩家点击时会有响应的事件产生。
创建Button的函数
创建Button 控件的函数有以下几种
public static bool Button(Rect position, string text);
public static bool Button(Rect position, Texture image);
public static bool Button(Rect position, GUIContent content);
public static bool Button(Rect position, string text, GUIStyle style);
public static bool Button(Rect position, Texture image, GUIStyle style);
public static bool Button(Rect position, GUIContent content, GUIStyle style);
参数的含义与之前的差不了太多,参照之前的文章
https://blog.csdn.net/qq_39485740/article/details/102537075
返回值
函数的返回值是布尔类型,他表示的是当这个按钮被点击时,则会返回true值,否则则为false值。
样例
using UnityEngine;
using System.Collections;
public class button_script1 : MonoBehaviour {
private string str;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnGUI () {
GUILayout.Label (str); //GUILayout可以不用我们去画出一个显示区域,系统会自动帮我们计算
if (GUI.Button (new Rect (50, 100, 80, 30), "button1")) {
str += "button1";
}
if (GUI.Button (new Rect (50, 140, 80, 30), "button2")) {
str += "button2";
}
}
}
显示效果
打开的界面:
点击button1后的界面:
点击按钮2后的界面:
特殊的Button控件——RepeatButton
创建RepeatButton的函数
public static bool RepeatButton(Rect position, string text);
public static bool RepeatButton(Rect position, Texture image);
public static bool RepeatButton(Rect position, GUIContent content);
public static bool RepeatButton(Rect position, string text, GUIStyle style);
public static bool RepeatButton(Rect position, Texture image, GUIStyle style);
public static bool RepeatButton(Rect position, GUIContent content, GUIStyle style);
Parameters
参数含义同上基本一致
返回值
函数的返回值是布尔类型,他表示的是当这个按钮被点击时,则会返回true值,否则则为false值。和Button不同的是他可以一直按住。
样例
using UnityEngine;
using System.Collections;
public class button_script2 : MonoBehaviour {
private int time;
private string str;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnGUI () {
GUILayout.Label (str);
if (GUI.RepeatButton (new Rect (30, 140, 120, 30), "请按住按钮")) {
time++;
str += time;
}
}
}
运行效果
没有按住按钮时
按住按钮时