Save e Load
File Access
extends Node
const SAVE_PATH = "user://savegame.save"
func save_game():
var save_data = {
"player_position": player.position,
"player_health": player.health,
"level": current_level,
"score": score
}
var file = FileAccess.open(SAVE_PATH, FileAccess.WRITE)
file.store_var(save_data)
file.close()
print("Game saved!")
func load_game():
if not FileAccess.file_exists(SAVE_PATH):
return false
var file = FileAccess.open(SAVE_PATH, FileAccess.READ)
var save_data = file.get_var()
file.close()
player.position = save_data["player_position"]
player.health = save_data["player_health"]
current_level = save_data["level"]
score = save_data["score"]
print("Game loaded!")
return true
JSON Save
func save_game_json():
var save_data = {
"player": {
"position": {"x": player.position.x, "y": player.position.y},
"health": player.health
},
"level": current_level,
"score": score
}
var file = FileAccess.open(SAVE_PATH, FileAccess.WRITE)
file.store_string(JSON.stringify(save_data))
file.close()
func load_game_json():
if not FileAccess.file_exists(SAVE_PATH):
return false
var file = FileAccess.open(SAVE_PATH, FileAccess.READ)
var json_string = file.get_as_text()
file.close()
var json = JSON.new()
var parse_result = json.parse(json_string)
if parse_result == OK:
var save_data = json.data
player.position = Vector2(
save_data["player"]["position"]["x"],
save_data["player"]["position"]["y"]
)
player.health = save_data["player"]["health"]
current_level = save_data["level"]
score = save_data["score"]
return true
return false
Auto-save
extends Node
var auto_save_timer: Timer
func _ready():
auto_save_timer = Timer.new()
add_child(auto_save_timer)
auto_save_timer.wait_time = 60.0 # 1 minuto
auto_save_timer.timeout.connect(_on_auto_save)
auto_save_timer.start()
func _on_auto_save():
save_game()
print("Auto-saved!")
Save Manager
class_name SaveManager
extends Node
const SAVE_DIR = "user://saves/"
const SAVE_EXTENSION = ".save"
static func save_game(slot: int, data: Dictionary):
if not DirAccess.dir_exists_absolute(SAVE_DIR):
DirAccess.make_dir_absolute(SAVE_DIR)
var save_path = SAVE_DIR + "slot_" + str(slot) + SAVE_EXTENSION
var file = FileAccess.open(save_path, FileAccess.WRITE)
file.store_var(data)
file.close()
static func load_game(slot: int) -> Dictionary:
var save_path = SAVE_DIR + "slot_" + str(slot) + SAVE_EXTENSION
if not FileAccess.file_exists(save_path):
return {}
var file = FileAccess.open(save_path, FileAccess.READ)
var data = file.get_var()
file.close()
return data
static func delete_save(slot: int):
var save_path = SAVE_DIR + "slot_" + str(slot) + SAVE_EXTENSION
if FileAccess.file_exists(save_path):
DirAccess.remove_absolute(save_path)
static func has_save(slot: int) -> bool:
var save_path = SAVE_DIR + "slot_" + str(slot) + SAVE_EXTENSION
return FileAccess.file_exists(save_path)
Best Practices
- user:// per save files
- JSON per human-readable saves
- Multiple save slots
- Auto-save periodico
- Versioning per compatibilità