2014-06-17 18 views
0

任何人都可以告訴我爲什麼我的庫存框沒有顯示出來嗎?如果用戶按下「庫存」按鈕,我希望庫存框顯示出來。我沒有收到任何錯誤,如果我把清單框放在if語句之外,它工作正常。統一GUI.Box在if語句後沒有顯示

using UnityEngine; 
using System.Collections; 

public class MyGUI : MonoBehaviour { 

    // Use this for initialization 
    void Start() { 

    } 

    // Update is called once per frame 
    void Update() { 

    } 

    void OnGUI() { 

     // Make a background for the button 

     GUI.Box (new Rect (10, 10, 100, 200), "Menu"); 

     // Make a button. 
     // Be able to click that button. 
     // If they click it return inventory screen. 

     if (GUI.Button (new Rect(20, 50, 75, 20), "Inventory")) { 

      Debug.Log("Your inventory opens"); 

      GUI.Box (new Rect (150, 10, 300, 200), "Inventory"); 

     } 

    } 
} 

回答

2

你的庫存箱沒有顯示出來,因爲OnGUI函數被調用每一幀,像更新。這意味着您的庫存矩形僅在點擊庫存按鈕時發生的OnGUI調用期間被繪製。

您可以使用布爾標誌來解決您的問題。

private bool _isInvetoryOpen = false; 

void OnGUI() { 
    GUI.Box (new Rect (10, 10, 100, 200), "Menu"); 

    // Toggle _isInventoryOpen flag on Inventory button click. 
    if (GUI.Button (new Rect (20, 50, 75, 20), "Inventory")) { 
     _isInvetoryOpen = !_isInvetoryOpen; 
    } 

    // If _isInventoryOpen is true, draw the invetory rectangle. 
    if (_isInvetoryOpen) { 
     GUI.Box (new Rect (150, 10, 300, 200), "Inventory"); 
    } 
} 

點擊庫存按鈕並在下列OnGUI調用期間繼續繪製或繪製該標誌時,該標誌被切換。

http://docs.unity3d.com/ScriptReference/GUI.Button.html

http://docs.unity3d.com/Manual/gui-Basics.html

+0

非常感謝!所以我明白爲什麼我的版本不起作用,但爲什麼當按鈕被第二次點擊時,庫存按鈕會消失?是否因爲OnGUI被重置並創建了一個全新的視圖?這似乎會浪費很多內存? –

+0

OnGUI函數正在重繪每個循環,並且該按鈕被設置爲在單擊時切換_isInventoryOpen。因此,當_isInventoryOpen爲false時,庫存框未繪製。它對內存沒有太大的影響,但對CPU有很大的影響。 http://answers.unity3d.com/questions/13433/performance-differences-in-unitygui-versus-guitext.html – davidjheberle