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

How can I tell which key or joystick button was pressed?

Discussion in 'Input System' started by EZaca, Jan 27, 2020.

  1. EZaca

    EZaca

    Joined:
    Dec 9, 2017
    Posts:
    31
    Hello, everyone!

    I have a question about how to make an "Options > Controls" screen like most games include. My game currently accepts a mouse, touch, keyboard, or joystick. Then the user can choose the controller s/he prefers and everything works fine, but I wish to allow him/her to tell which key on the keyboard or Joystick button s/he wants to perform each action.

    I don't know any way to do that! How to tell which key/joystick button the player has pressed, so I can update the control preferences in the game?
     
  2. Rene-Damm

    Rene-Damm

    Unity Technologies

    Joined:
    Sep 15, 2012
    Posts:
    1,779
    JeremyToler and EZaca like this.
  3. EZaca

    EZaca

    Joined:
    Dec 9, 2017
    Posts:
    31
    "Rebind", that's the word I was looking for ^^'

    Thank you for the content, it surely will help a lot! :)
     
  4. EZaca

    EZaca

    Joined:
    Dec 9, 2017
    Posts:
    31
    **UPDATE**:
    It is really simple to rebind a key with that! While the video and Unity samples help a lot, I want to share this very simple code snippet I managed to work:

    Code (CSharp):
    1. InputAction action = myPlayerInput.actions.FindAction("MyAction");
    2. action.Disable();
    3.  
    4. var rebinder = action.PerformInteractiveRebinding(/* binding index to override */)
    5. .OnComplete(operation => {
    6.     action.Enable();
    7.     Debug.Log("Rebind completed!");
    8.     operation.Dispose();
    9. })
    10. .OnCancel(operation => {
    11.     action.Enable();
    12.     Debug.Log("Rebind cancelled!");
    13.     operation.Dispose();
    14. });
    15.  
    16. rebinder.Start();
    17. Debug.Log("Waiting for input...");
    *Notice it is a very very simplified snippet. For more complex examples, follow Rene-Damm link.
     
    Last edited: Jan 27, 2020
    JeremyToler likes this.