KeyPersistence.gd 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. # This is an autoload (singleton) which will save
  2. # the key maps in a simple way through a dictionary.
  3. extends Node
  4. const keymaps_path := "user://keymaps.dat"
  5. var keymaps: Dictionary
  6. func _ready() -> void:
  7. # First we create the keymap dictionary on startup with all
  8. # the keymap actions we have.
  9. for action in InputMap.get_actions():
  10. if not InputMap.action_get_events(action).is_empty():
  11. keymaps[action] = InputMap.action_get_events(action)[0]
  12. load_keymap()
  13. func load_keymap() -> void:
  14. if not FileAccess.file_exists(keymaps_path):
  15. # There is no save file yet, so let's create one.
  16. save_keymap()
  17. return
  18. var file := FileAccess.open(keymaps_path, FileAccess.READ)
  19. var temp_keymap: Dictionary = file.get_var(true)
  20. file.close()
  21. # We don't just replace the keymaps dictionary, because if you
  22. # updated your game and removed/added keymaps, the data of this
  23. # save file may have invalid actions. So we check one by one to
  24. # make sure that the keymap dictionary really has all current actions.
  25. for action: StringName in keymaps.keys():
  26. if temp_keymap.has(action):
  27. keymaps[action] = temp_keymap[action]
  28. # Whilst setting the keymap dictionary, we also set the
  29. # correct InputMap event.
  30. InputMap.action_erase_events(action)
  31. InputMap.action_add_event(action, keymaps[action])
  32. func save_keymap() -> void:
  33. # For saving the keymap, we just save the entire dictionary as a var.
  34. var file := FileAccess.open(keymaps_path, FileAccess.WRITE)
  35. file.store_var(keymaps, true)
  36. file.close()