Unity GUI.Box在if语句后不显示

时间:2014-06-17 17:07:07

标签: c# user-interface unity3d

有谁能告诉我为什么我的库存盒子没有出现?如果用户按下库存按钮,我希望显示库存框。我没有收到任何错误,如果我将库存框放在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");

        }

    }
}

1 个答案:

答案 0 :(得分:2)

您的广告资源框未显示,因为每一帧都会调用OnGUI函数,例如Update。这意味着您的库存矩形仅在单击库存按钮时发生的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