Godot Version
v4.7-stable_mono_linux
OS: EndeavourOS v26.4-1-1
Question
Hello, I tried to use a json file to save some changeable configuration on my game, it works on debbug, but when I export it, it seems it does not write into the json file.
The game can load the json file correctly, because some text labels are directly displaying what is on the file, but whenever I try to change what is written, it does not work.
This is the code that I use to manipulate my json file.
# Declarar variáveis
var gamedata: Dictionary = {} # Gamedata
var gamedata_path = "res://gamedata/gamedata.json" # Caminho para o arquivo
# Função ready
func _ready():
gamedata = load_json_file(gamedata_path)
# Função de atualizar o .json
func update_stats():
print(gamedata)
write_json_file(gamedata, gamedata_path)
# Carregar os dados do jogo
func load_json_file(filePath: String):
if FileAccess.file_exists(filePath):
# Ler gamedata
var dataFile = FileAccess.open(filePath, FileAccess.READ)
var parsedResult = JSON.parse_string(dataFile.get_as_text())
# Retornar dados
if parsedResult is Dictionary:
dataFile.close()
return parsedResult
else:
print("Erro ao carregar os dados!")
dataFile.close()
else:
print("O arquivo <gamedata.json> não existe!")
# Escrever dados do jogo no gamedata
func write_json_file(data: Dictionary, filePath: String):
# Abrir arquivo
var dataFile = FileAccess.open(filePath, FileAccess.WRITE)
# Escrever novos dados
var json_text = JSON.stringify(data, "\t")
dataFile.store_string(json_text)
dataFile.close()
And this is the part where I try to change it:
# Salvar alterações de jogo
func _on_save_config_pressed() -> void:
$Gamedata.gamedata["players"] = str(num_players)
$Gamedata.gamedata["enemies"] = str(num_enemies)
if FileAccess.file_exists("res://gamedata/gamedata.json"):
$Gamedata.update_stats()
else:
print("Falha")
get_tree().quit()
$Texto/Aviso.text = "Configurações salvas!"
As you can see, I tried to see if the json file was being deleted for some reason and tried to make the game close if it didn’t exist.
I know that there are another methods of doing this, I don’t need to use json file, but I wanted to learn how to use, since I want to develop a more complex game afterwards and using json files would be more ideal in this future case.
I appreciate any help regarding my problem and apologize if have any mistakes in my request or if I did not sound clear in my explanation!
PS. If it is needed, the comments in the code are in Portuguese