save_load_config_file.gd 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. extends Button
  2. # This script shows how to save data using Godot's custom ConfigFile format.
  3. # ConfigFile can store any Variant type except Signal or Callable.
  4. # It can even store Objects, but be extra careful where you deserialize them
  5. # from, because they can include (potentially malicious) scripts.
  6. const SAVE_PATH = "user://save_config_file.ini"
  7. ## The root game node (so we can get and instance enemies).
  8. @export var game_node: NodePath
  9. ## The player node (so we can set/get its health and position).
  10. @export var player_node: NodePath
  11. func save_game():
  12. var config := ConfigFile.new()
  13. var player := get_node(player_node) as Player
  14. config.set_value("player", "position", player.position)
  15. config.set_value("player", "health", player.health)
  16. config.set_value("player", "rotation", player.sprite.rotation)
  17. var enemies := []
  18. for enemy in get_tree().get_nodes_in_group(&"enemy"):
  19. enemies.push_back({
  20. position = enemy.position,
  21. })
  22. config.set_value("enemies", "enemies", enemies)
  23. config.save(SAVE_PATH)
  24. (get_node(^"../LoadConfigFile") as Button).disabled = false
  25. func load_game():
  26. var config := ConfigFile.new()
  27. config.load(SAVE_PATH)
  28. var player := get_node(player_node) as Player
  29. player.position = config.get_value("player", "position")
  30. player.health = config.get_value("player", "health")
  31. player.sprite.rotation = config.get_value("player", "rotation")
  32. # Remove existing enemies before adding new ones.
  33. get_tree().call_group("enemy", "queue_free")
  34. var enemies = config.get_value("enemies", "enemies")
  35. var game = get_node(game_node)
  36. for enemy_config in enemies:
  37. var enemy := preload("res://enemy.tscn").instantiate() as Enemy
  38. enemy.position = enemy_config.position
  39. game.add_child(enemy)