OnGUI Toggle控件

2020-07-13 15:25 更新

Unity 3D Toggle 控件用于在屏幕上繪制一個開關(guān),通過控制開關(guān)的開啟與閉合來執(zhí)行一些具體的指定操作。

當(dāng)用戶切換開關(guān)狀態(tài)時,Toggle 控件的繪制函數(shù)就會根據(jù)不同的切換動作來返回相應(yīng)的布爾值。

如選中 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 為默認控件是開還是關(guān)。

  • text 為控件顯示的字符內(nèi)容。

參數(shù)列表

參數(shù) 描述
position 設(shè)置控件在屏幕上的位置及大小。
image 設(shè)置控件上顯示的紋理圖片。
style 設(shè)置控件使用的樣式。
text 設(shè)置控件上顯示的文本。
content 置控件的文本、圖片和提示小。
value 設(shè)置開關(guān)是開啟還是關(guān)閉。

使用案例

  1. 創(chuàng)建項目,將其命名為 GUI.Toggle,保存場景。

  1. 執(zhí)行 AssetsCreateJavaScript 命令,創(chuàng)建一個新的腳本文件。

  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. 進行測試,效果如下圖所示。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號