Can someone explain why my function returns null?

4.5

So I haven’t done a lot of work with saving/loading data with FileAccess and my code is returning null and I have no idea why

Here’s my code:

extends Control

@onready var start_game: Button = $"MarginContainer/HBoxContainer/VBoxContainer/Start Game"
@onready var exit_game: Button = $"MarginContainer/HBoxContainer/VBoxContainer/Exit Game"
@onready var level_1 = "res://Level 1/level_1.tscn"
@onready var level_2 = "res://Level 2/level_2.tscn"
@onready var level_3 = "res://Level 3/level_3.tscn"
@onready var current_level = "res://Level 1/level_1.tscn"

var save_path = "res://Data/Save Game.txt"

func  _ready() -> void:
	pass

func exit_game_pressed() -> void:
	get_tree().quit()

func start_game_pressed() -> void:
	current_level = load_data()  # Dynamically load the level path
	print(current_level)
	var packed_scene = load(current_level)  
	if packed_scene:
		get_tree().change_scene_to_packed(packed_scene)  
		print("Start game pressed")
	else:
		print("Error: Failed to load scene at path:", current_level)

func load_data():
	var saved_level
	if FileAccess.file_exists(save_path):
		var file = FileAccess.open(save_path, FileAccess.READ)
		saved_level = file.get_var(true)
		print(saved_level)
		return saved_level
	else:
		print("No Save Data Exists")
		saved_level = "res://level_1.tscn"
		return saved_level

func save():
	var file = FileAccess.open(save_path, FileAccess.WRITE)
	file.store_var(current_level, true)
	file.close()
	print("Stored level: ", current_level)
2 Likes

It fails because save() attempts to open save_path which contains a directory called Data which doesn’t exist beforehand. FileAccess will not create directories on its own, it will simply fail with FILE_DOES_NOT_EXIST if the directory isn’t there beforehand.

You also do not want your save files in the res:// directory (as that is the project’s internal directory which you will not be able to write to after exporting), you want them in the user:// directory.

The solution? Check and create the needed dir structure beforehand using DirAccess, or simply change the save_path to something like "user://save game.txt" just to make sure everything works.

1 Like

ok i will try it and report back

all i did was change the res:// to user:// for anyone else who might be reading this to help fix their problem and that seems to have worked thank you so much