【问题标题】:Unity GUI.Box not showing up after if statement如果语句后未显示 Unity GUI.Box
【发布时间】:2014-08-07 19:22:27
【问题描述】:

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

        }

    }
}

【问题讨论】:

    标签: c# user-interface unity3d


    【解决方案1】:

    您的库存箱没有显示,因为 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

    【讨论】:

    • 非常感谢!所以我明白为什么我的版本不起作用,但是为什么当第二次单击按钮时库存按钮会消失?是因为 OnGUI 被重置并创建了一个全新的视图吗?这样好像会浪费很多内存?
    • OnGUI 函数正在重绘每个循环,并且按钮设置为在单击时切换 _isInventoryOpen。因此,当 _isInventoryOpen 为 false 时,不会绘制 Inventory 框。它对内存的影响并不大,但对 CPU 的影响却很大。 answers.unity3d.com/questions/13433/…
    【解决方案2】:

    @davidjheberle 是正确的,因为这是因为对OnGUI 的重复调用;但值得一提的是,在现代 Unity 中,您还可以使用 GUI.RepeatButtonGUI.RepeatButton 几乎与GUI.Button 相同,除了在每一帧检查鼠标按钮按下的状态,而不仅仅是初始单击的帧。因此,至少对于 Unity 2020.3 及之后的版本,以下代码也可以使用:

        void OnGUI () {
    
        GUI.Box (new Rect (10, 10, 100, 200), "Menu");
    
        //Note the difference here-- we are using a RepeatButton instead
        if (GUI.RepeatButton (new Rect(20, 50, 75, 20), "Inventory")) {
    
            Debug.Log("Your inventory opens");
    
            GUI.Box (new Rect (150, 10, 300, 200), "Inventory");
    
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2013-02-11
      • 1970-01-01
      • 2019-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多