codecamp

OnGUI Toggle控件

Unity 3D Toggle 控件用于在屏幕上绘制一个开关,通过控制开关的开启与闭合来执行一些具体的指定操作。

当用户切换开关状态时,Toggle 控件的绘制函数就会根据不同的切换动作来返回相应的布尔值。

如选中 Toggle 控件会返回布尔值 true,取消选中就会返回布尔值 false

具体使用方法如下:

public static function Toggle(position:Rect, value:bool, text:string):bool;
public static function Toggle(position:Rect, value:bool, image:Texture):bool;
public static function Toggle(position:Rect, value:bool, content:GUIContent):bool;
public static function Toggle(position:Rect, value:bool, text:string, style:GUIStyle):bool;
public static function Toggle(position:Rect, value:bool, image:Texture, style:GUIStyle):bool;
public static function Toggle(position:Rect, value:bool, content:GUIContent,style:GUIStyle):bool;

注:

  • position 为控件显示位置。

  • value 为默认控件是开还是关。

  • text 为控件显示的字符内容。

参数列表

参数 描述
position 设置控件在屏幕上的位置及大小。
image 设置控件上显示的纹理图片。
style 设置控件使用的样式。
text 设置控件上显示的文本。
content 置控件的文本、图片和提示小。
value 设置开关是开启还是关闭。

使用案例

  1. 创建项目,将其命名为 GUI.Toggle,保存场景。

  1. 执行 AssetsCreateJavaScript 命令,创建一个新的脚本文件。

  1. 在 Project 视图中打开脚本编辑器,输入下列语句:

    var aTexture:Texture;
    private var toggleTxt:boolean=false;
    private var toggleImg:boolean=false;
    function OnGUI(){
        if(!aTexture){
            Debug.LogError("Please assign a texture in the inspector.");
            return;
        }
        toggleTxt=GUI.Toggle(Rect(10, 10, 100, 30), toggleTxt, "A Toggle text");
        toggleImg=GUI.Toggle(Rect(10, 50, 50, 50), toggleImg, aTexture);
    }

  1. Ctrl+S 键保存脚本。

  1. 在 Project 视图中选择脚本,将其连接到 Main Camera 上。

  1. 在 Inspector 视图中添加纹理资源。

  1. 进行测试,效果如下图所示。

OnGUI Skin控件
UGUI Canvas 画布
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }