Godot Version
4.2.2
Question
Hello all,
I’m currently trying to figure out a solution to my following problem.
Hoping the good people here could provide some insight on achieving the desired result.
I’ve followed a tutorial and implemented a save and load system for my game, using resources.
The following is the structure I’ve created. The following stats will be saved to a file.
PlayerData.gd - Resource file
extends Resource
class_name PlayerData
@export var current_lives: int = 3
@export var max_health: int = 10
@export var current_health: int = max_health
@export var current_shield_amount: int = 0
@export var current_grenade_count: int = 0
@export var current_score: int
@export var current_spawn_pos: Vector2
The “Save” and “Load” functions are located in the player script.
Player.gd - Only included the code snippets relevant to the question.
extends CharacterBody2D
class_name Player
var save_file_path = "user://save/"
var save_file_name = "PlayerSave.tres"
var playerData = PlayerData.new()
func _ready():
verify_save_directory(save_file_path)
func _physics_process(delta):
//No code relevant to the question included here
func verify_save_directory(path: String):
DirAccess.make_dir_absolute(path)
func load_data():
playerData = ResourceLoader.load(save_file_path + save_file_name).duplicate(true)
print("loaded")
func save_data():
ResourceSaver.save(playerData, save_file_path + save_file_name)
print("save :" + str( playerData, save_file_path + save_file_name))
Also, there is a Main menu screen with a “Load Game” button.
This should ideally load the game, and update player stats according to what’s there in the save file.
MainMenu.gd
extends Node2D
const START_LEVEL = preload("res://Levels/Level_01.tscn")
@onready var btn_new_game = $VBoxContainer/Btn_NewGame
@onready var btn_load_game = $VBoxContainer/Btn_LoadGame
@onready var btn_quit = $VBoxContainer/Btn_Quit
# Called when the node enters the scene tree for the first time.
func _ready():
pass
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
pass
func _on_btn_load_game_pressed():
get_tree().change_scene_to_file("res://Levels/Level_01.tscn")
Can any of you please guide me on how to achieve this?
Once the player clicks on the “Load Game” button, the level should load and update the player’s stats with what the resource file contains.
Any help on this would be much appreciated.