KeyPersistence.gd 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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 InputMap.action_get_events(action).size() != 0:
  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. save_keymap() # There is no save file yet, so let's create one.
  16. return
  17. var file = FileAccess.open(keymaps_path, FileAccess.READ)
  18. var temp_keymap = file.get_var(true) as Dictionary
  19. file.close()
  20. # We don't just replace the keymaps dictionary, because if you
  21. # updated your game and removed/added keymaps, the data of this
  22. # save file may have invalid actions. So we check one by one to
  23. # make sure that the keymap dictionary really has all current actions.
  24. for action in keymaps.keys():
  25. if temp_keymap.has(action):
  26. keymaps[action] = temp_keymap[action]
  27. # Whilst setting the keymap dictionary, we also set the
  28. # correct InputMap event
  29. InputMap.action_erase_events(action)
  30. InputMap.action_add_event(action, keymaps[action])
  31. func save_keymap() -> void:
  32. # For saving the keymap, we just save the entire dictionary as a var.
  33. var file := FileAccess.open(keymaps_path, FileAccess.WRITE)
  34. file.store_var(keymaps, true)
  35. file.close()