Unity3D GUI键盘导航

时间:2012-08-25 00:58:46

标签: user-interface input keyboard unity3d

我的菜单脚本编码功能允许组合菜单的按钮被导航(通过GUI.FocusControl()将焦点从按钮更改为按钮)。但是,我对如何“激活”/“选择”当前关注的按钮感到困惑。理想地,用户可以在菜单中上下导航并在用户处于他或她希望选择的选项时按下“输入”。任何建议都会很棒。

1 个答案:

答案 0 :(得分:0)

我花了一段时间才弄清楚如何做到这一点,但最终我找到了解决方案。如果你还在寻找答案,我就是这样做的。基本上你想要使用GUI类的SelctionGrid函数。您可以使用高峰here来查看其工作原理,但这里有一些代码,其中包含您所要求的工作示例:

#pragma strict
@script ExecuteInEditMode;

var selGridInt : int = 0;    //This integer is the index of the button we are hovering above or have selected

var selStrings : String[] = ["Grid 1", "Grid 2", "Grid 3", "Grid 4"];

private var maxButton : int;    // The total number of buttons in our grid

function Start()
{
    maxButton = selStrings.Length;    // Set the total no. of buttons to our String array size
}

function Update()
{
    // Get keyboard input and increase or decrease our grid integer
    if(Input.GetKeyUp(KeyCode.UpArrow))
    {
        // Here we want to create a wrap around effect by resetting the selGridInt if it exceeds the no. of buttons
        if(selGridInt > 0)
        {
            selGridInt--;
        }
        else
        {
            selGridInt = maxButton - 1;
        }
    }

    if(Input.GetKeyUp(KeyCode.DownArrow))
    {
        // Create the same wrap around effect as above but alter for down arrow
        if(selGridInt < (maxButton-1))
        {
            selGridInt++;
        }
        else
        {
            selGridInt = 0;
        }
    }

    if(Input.GetKeyUp(KeyCode.Return))
    {
        switch(selGridInt)
        {
            case 0: Debug.Log("Button "+(selGridInt + 1 )+ " pressed.");
                break;
            case 1: Debug.Log("Button "+(selGridInt + 1 )+" pressed.");
                break;
            case 2: Debug.Log("Button "+(selGridInt + 1 )+ " pressed.");
                break;
            case 3: Debug.Log("Button "+(selGridInt + 1 )+ " pressed.");
                break;
        }
    }
}

function OnGUI () 
{
    selGridInt = GUI.SelectionGrid (Rect (Screen.width/2-75, Screen.height/2-25, 150, 200), selGridInt, selStrings, 1);
}