Saving and loading a level for 2D platformer Godot

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Northeast

I am having trouble loading a 2d platformer level upon pressing the load button on the main menu.

func _ready():
_load()

For Loading

var level = 0
var pause = false

func _load():
var new_file = File.new()
if not new_file.file_exists("res://game_save.txt"):
	_save()
	return
new_file.open("res://game_save.txt", File.READ)
var data = new_file.get_as_text()
new_file.close()
data = data.split("\n")
for line in data:
	if line.begins_with("level"):
		level = int(line.split(" ")[1])

func _on_Load_pressed():
_load()

For Saving

func _save():
var data = ""
data += "level " + str(level)
var new_file = File.new()
new_file.open("res://game_save.txt", File.WRITE)
new_file.store_line(data)
new_file.close()

All I want is to save the level, which is done by pressing the save button in the pause menu. Right now, nothing happens after pressing the load button…
Can anyone help me??

:bust_in_silhouette: Reply From: jgodfrey

You should store game save info in user://, not res://. I assume your code is failing because res:// isn’t accessible. Additionally, the open call returns an Error that you should be checking for failure. So, something like:

var res = new_file.open("user://game_save.txt", File.WRITE)
if res != OK:
    print("file open failed with error: %s" % res)
else:
    # file open is successful