使用下拉菜单Unity隐藏/显示面板

时间:2019-04-19 11:36:22

标签: c# unity3d

我刚刚启动了一些基本游戏项目的统一项目。

这可能是错误的问题或无效的过程。

单击按钮后我已经完成了隐藏/显示面板,现在我想在下拉菜单的值更改后隐藏/显示。

我有两个面板,一个用于基本信息,另一个用于安全信息。选择下拉值后,我要显示这些面板之一并隐藏第二个面板。

但是我不知道如何实现。

我正在尝试一些基本逻辑并坚持下去。

我做了什么:

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using System.Collections;

public class WithrowModalPanel : MonoBehaviour
{

    public Button cancelButton;
    public GameObject modalPanelObject;
    public GameObject modalPanelObjectAdvance;
    public Dropdown myDropdown;

    private static WithrowModalPanel modalPanel;

    public static WithrowModalPanel Instance()
    {
        if (!modalPanel)
        {
            modalPanel = FindObjectOfType(typeof(WithrowModalPanel)) as WithrowModalPanel;
            if (!modalPanel)
                Debug.LogError("There needs to be one active ModalPanel script on a GameObject in your scene.");
        }

        return modalPanel;
    }

    void Update()
    {
        switch (myDropdown.value)
        {
            case 1:
                Debug.Log("Basic panel!");
                modalPanelObject.SetActive(true);
                modalPanelObjectAdvance.SetActive(false);
                break;

            case 2:
                Debug.Log("Advance panel!");
                modalPanelObjectAdvance.SetActive(true);
                modalPanelObject.SetActive(false);
                break;
        }
    }
}

我只是凝视着团结,对它的结构并不了解。

1 个答案:

答案 0 :(得分:1)

请注意,Dropdown.value是从0开始的索引,因此第一个条目是0而不是1。我不知道您的完整设置,但我想这是您尝试中的主要问题。

然后下拉列表有一个事件onValueChanged,而不是在Update中进行,您应该注册一个监听器

private void Start()
{
    // Just to be sure it is allways only added once
    // I have the habit to remove before adding a listener
    // This is valid even if the listener was not added yet
    myDropdown.onValueChanged.RemoveListener(HandleValueChanged);
    myDropdown.onValueChanged.AddListener(HandleValueChanged);
}

private void OnDestroy()
{
    // To avoid errors also remove listeners as soon as they
    // are not needed anymore
    // Otherwise in the case this object is destroyed but the dropdown is not
    // it would still try to call your listener -> Exception
    myDropdown.onValueChanged.RemoveListener(HandleValueChanged);
}

private void HandleValueChanged(int newValue)
{
    switch (newValue)
    {
        case 0:
            Debug.Log("Basic panel!");
            modalPanelObject.SetActive(true);
            modalPanelObjectAdvance.SetActive(false);
            break;

        case 1:
            Debug.Log("Advance panel!");
            modalPanelObjectAdvance.SetActive(true);
            modalPanelObject.SetActive(false);
            break;
    }
}

提示:您可以使用FindObjectOfType的泛型

modalPanel = FindObjectOfType<WithrowModalPanel>();