save_load_json.gd 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. extends Button
  2. # This script shows how to save data using the JSON file format.
  3. # JSON is a widely used file format, but not all Godot types can be
  4. # stored natively. For example, integers get converted into doubles,
  5. # and to store Vector2 and other non-JSON types you need to convert
  6. # them, such as to a String using var_to_str.
  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. const SAVE_PATH = "user://save_json.json"
  12. func save_game():
  13. var file := FileAccess.open(SAVE_PATH, FileAccess.WRITE)
  14. var player = get_node(player_node)
  15. # JSON doesn't support many of Godot's types such as Vector2.
  16. # var_to_str can be used to convert any Variant to a String.
  17. var save_dict = {
  18. player = {
  19. position = var_to_str(player.position),
  20. health = var_to_str(player.health),
  21. rotation = var_to_str(player.sprite.rotation)
  22. },
  23. enemies = []
  24. }
  25. for enemy in get_tree().get_nodes_in_group(&"enemy"):
  26. save_dict.enemies.push_back({
  27. position = var_to_str(enemy.position),
  28. })
  29. file.store_line(JSON.stringify(save_dict))
  30. get_node(^"../LoadJSON").disabled = false
  31. func load_game():
  32. var file := FileAccess.open(SAVE_PATH, FileAccess.READ)
  33. var json := JSON.new()
  34. json.parse(file.get_line())
  35. var save_dict := json.get_data() as Dictionary
  36. var player := get_node(player_node) as Player
  37. # JSON doesn't support many of Godot's types such as Vector2.
  38. # str_to_var can be used to convert a String to the corresponding Variant.
  39. player.position = str_to_var(save_dict.player.position)
  40. player.health = str_to_var(save_dict.player.health)
  41. player.sprite.rotation = str_to_var(save_dict.player.rotation)
  42. # Remove existing enemies before adding new ones.
  43. get_tree().call_group("enemy", "queue_free")
  44. # Ensure the node structure is the same when loading.
  45. var game := get_node(game_node)
  46. for enemy_config in save_dict.enemies:
  47. var enemy = preload("res://enemy.tscn").instantiate()
  48. enemy.position = str_to_var(enemy_config.position)
  49. game.add_child(enemy)