How do I get the name of the pressed button?

I’d like to retrieve the name of the action corresponding to the pressed gamepad button.

 var myAction = new InputAction(binding: "/*/<button>");
myAction.onPerformed += (action, control) => Debug.Log($"Button {control.name} pressed!");
myAction.Enable();

…from the docs doesn’t seem to work. It throws an error.

Any help would be appreciated. Cheers.

This works. Is there a more efficient way? And how can I restrict this to gamepad button presses?

InputSystem.onActionChange +=
    (obj, change) =>
    {
        Debug.Log($"{((InputAction) obj).name} {change}");
    };

I believe the onPerformed event uses a CallbackContext, which has many properties. One of which is action, which is a reference to the InputAction which it belongs to. The InputAction has a property called name which is the Action’s name. So you can try something like this:

myAction.onPerformed += ctx => Debug.Log(ctx.action.name);

You can pass the whole context as a parameter into a method of your choosing, and get all sorts of info about what caused the action to fire.

1 Like

Cheers @SomeGuy22 . Does that code need to go anywhere particular? Update?

And in this case, will myAction always correspond to the latest pressed button?

Btw @Rene-Damm looks like the “how do I…?” docs need some updating as onPerformed is now performed

myAction.performed += ctx => Debug.Log(ctx.action.name);

It’s a C# event subscription. Do not put anything like this in an Update loop. You need to subscribe once (per receiving object) and you need to unsubscribe when you’re done (unless you truly need the subscription until the exit of the application).

It is about actions. So when you have a “Fire” action to shoot, and the player activate this action through the button/key you set for the action, this delegate will be invoked and the context will tell you what triggered the action.
This will not give you any arbitrary key- or button-presses outside of the scope of this action.
All this information is about one action (button press or joystick move or whatever).

If you only want to show the gamepad button presses, first, you need to restrict your action to the game pad OR you can read the used device through the control property of the context.

2 Likes

Cheers @ !

1 Like