Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Input.GetButton handling

Discussion in 'Scripting' started by sayhiJON, Aug 15, 2017.

  1. sayhiJON

    sayhiJON

    Joined:
    Sep 19, 2016
    Posts:
    5
    In setting up controller support it dawned on me that I do not have a good way of determining button presses over old button presses.

    As an example:

    Code (CSharp):
    1. // Update is called once per frame
    2.     void Update () {
    3.         if (Input.GetButton("A"))
    4.             uiText.text = "A was pressed";
    5.         else if (Input.GetButton("B"))
    6.             uiText.text = "B was pressed";
    7.         else if (Input.GetButton("X"))
    8.             uiText.text = "X was pressed";
    9.         else if (Input.GetButton("Y"))
    10.             uiText.text = "Y was pressed";
    11.         else
    12.             uiText.text = "Press any button to START";
    13.     }
    If "A" is pressed and held, B, X, and Y will never be caught by this. While there may not be a reason to hold "A," I would still like to know a better way (such as event driven reacting to each button press/release).

    Should I just remove the "else?" Of course this would lead to the issue that if "Y" is pressed and held, the text will never display "A" being pressed but, obviously, I could still process the "A" press.

    Any suggestions for handling that?
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,400
    Use GetButtonDown to toggle a state, then toggle it back with GetButtonUp.

    --Eric
     
  3. sayhiJON

    sayhiJON

    Joined:
    Sep 19, 2016
    Posts:
    5
    Okay, thanks.