按下多个按钮时检测

时间:2017-09-28 09:05:19

标签: c# unity3d

我希望我的问题不重复。 我有两个按钮。 我想在页面上单击两个按钮后进行操作。按下按钮的时间可能不同。 请帮我举个例子。

1 个答案:

答案 0 :(得分:3)

按下按钮时,为每个设置为true的按钮都有一个简单的布尔变量。然后,您可以检查Update函数中的两个布尔变量是否都为真。

附加到空的GameObject并将两个按钮拖到插槽中:

public Button button1;
public Button button2;

bool button1Pressed = false;
bool button2Pressed = false;

void OnEnable()
{
    //Register Button Events
    button1.onClick.AddListener(() => buttonCallBack(button1));
    button2.onClick.AddListener(() => buttonCallBack(button2));

}

private void buttonCallBack(Button buttonPressed)
{
    if (buttonPressed == button1)
    {
        //Your code for button 1
        Debug.Log("Clicked: " + button1.name);
        button1Pressed = true;
    }

    if (buttonPressed == button2)
    {
        //Your code for button 2
        Debug.Log("Clicked: " + button2.name);
        button2Pressed = true;
    }
}

void Update()
{
    //Check if both buttons have been pressed
    if (button1Pressed && button2Pressed)
    {
        //Do something
        Debug.Log("BOTH BUTTONS HAVE BEEN PRESSED");

        //Set both to false
        button1Pressed = false;
        button2Pressed = false;
    }
}