0 votes

How could I save/load input map to/from the disk to enable player to setup his own controls?

in Engine by (692 points)

1 Answer

0 votes

Hey there, this is the first thing that comes up when I googled this topic, so here is a reply. Basically, you need to save all the important properties, for each event associated with an action, then when loading, create the object, set the properties, then add it back to the action map... if this was python I'd just pickle the object, but it isn't, so here we are.

#--- Persistence
# example myPath = "user://settings_control_action_"+ActionX.text+".json"
func save_to_disk():
    var fileX = File.new()
    fileX.open(myPath,File.WRITE)
    for event in InputMap.get_action_list(ActionX.text):
        if event is InputEventKey:
            var toStore ={
                "type":"InputEventKey",
                "device":event.device,
                "alt":event.alt,
                "command":event.command,
                "control":event.control,
                "meta":event.meta,
                "shift":event.shift,
                "echo":event.echo,
                "pressed":event.pressed,
                "scancode":event.scancode,
                "unicode":event.unicode
            }
            fileX.store_line(to_json(toStore))
    fileX.close()

func load_from_disk():
    var fileX = File.new()
    if not fileX.file_exists(myPath):
        return
    InputMap.action_erase_events(ActionX.text)
    fileX.open(myPath,File.READ)
    while fileX.get_position() < fileX.get_len():
        var toSet = parse_json(fileX.get_line())
        if toSet["type"] == "InputEventKey":
            var event = InputEventKey.new()
            event.device = toSet["device"]
            event.alt = toSet["alt"]
            event.command = toSet["command"]
            event.control = toSet["control"]
            event.meta = toSet["meta"]
            event.shift = toSet["shift"]
            event.echo = toSet["echo"]
            event.pressed = toSet["pressed"]
            event.scancode = toSet["scancode"]
            event.unicode = toSet["unicode"]
            InputMap.action_add_event(ActionX.text,event)
            KeyChangeButton.text = OS.get_scancode_string(event.scancode)
    fileX.close()
by (50 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.