How to set an InputEventKey keybind to the InputMap in code?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Gurfy Person

I am loading keybinds from a file and I want to set them into the InputMap, but when I do it using InputMap.action_add_event() it doesn’t add, when I press the key nothing happens.

Here is my code for setting keybinds:

func _input(event):
if event is InputEventKey and selected:
	keybind = OS.get_scancode_string(event.unicode)
	selected = false

After that I save everything to a file when the window is closed.
Then to set a keybind I use this code:

func set_specific_keybind(action, keybind): # Sets a specific keybind
delete_specific_keybind(action)
var key = InputEventKey.new()
key.scancode = int(keybind)
InputMap.action_add_event(action, key)

Delete_specific_keybind just calls InputMap.action_erase_events().

If anyone has a solution for this, that would be helpful, it’s probably some silly mistake that I made.

:bust_in_silhouette: Reply From: Wakatta

Not sure why you use conversions

func set_specific_keybind(action, keybind): # Sets a specific keybind
    if not InputMap.get_actions().has(action):
        InputMap.add_action(action)
    delete_specific_keybind(action)
    var key = InputEventKey.new()
    key.set_scancode(keybind)
    InputMap.action_add_event(action, key)

Keybinds

func _input(event):
    if event is InputEventKey and selected:
        keybind = event.get_scancode()
        selected = false

Since int(keybind) won’t return a Unicode representation of that string and what you’re most likely looking for is

key.scancode = ord(keybind)

Wakatta | 2023-01-04 01:33

Oh thanks, I see the problem I had now.

Gurfy Person | 2023-01-04 23:30