get var from file

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

I made a save and load system but i want to get the values from each slot directly from file

extends Node

const file_path = "res://saves/"
var file_name = "res://saves/slot_00.dat"
var game_data = {}

func save_slot():
	var file = File.new()
	file.open_encrypted_with_pass(file_name, File.WRITE, "J7Çhri$Tº")
	file.store_var(game_data)
	file.close()
	print(game_data)

func load_slot():
	var file = File.new()
	if not file.file_exists(file_name):
		game_data = {
			"health": 0,
		}
		save_slot()
	file.open_encrypted_with_pass(file_name, File.READ, "J7Çhri$Tº")
	game_data = file.get_var()
	file.close()
	print(game_data)

func set_slot(slot):
	game_data = {}
	file_name = file_path + slot

My code generate a file called “slot01.dat” this file contains var, and my load game screen has four slots, i want to put the informations of “slot01.dat” in their respective labels and the same for “slot02.dat”, “slot03.dat” and “slot_04.dat”. Detail, i want to take the information directly from files.

What do you mean by “get the values from each slot directly from file”? You already have file.get_var(), can you add example of what you have and what you want?

AlexTheRegent | 2022-03-18 07:26

I would highly suggest you check the return values of open. Files can fail to open for a variety of reasons.

var err = file.open_encrypted_with_pass(...)
if err != OK:
	push_error(str("Could not open file, error ", err))

Note: the subdirectory saves/ will not be created automatically by the open call. If it does not exist, you might have to create it first using the Directory class (which itself returns error codes you should check).

Zylann | 2022-03-18 13:55

My code generate a file called “slot_01.dat” this file contains var, and my load game screen has four slots, i want to put the informations of “slot_01.dat” in their respective labels and the same for “slot_02.dat”, “slot_03.dat” and “slot_04.dat”. Detail, i want to take the information directly from files.

VinicOliver8394 | 2022-03-18 19:36