Can't create a new user:// file for score system using FileAccess.open()

Godot Version

Godot 4.3

Question

So in my score node (located in my game scene), I’m trying to implement a save_score function using FileAccess.open() so that I can display the score and high score after the game is over.

However, it seems that each time I try to create a user:// file to store my score data, FileAccess.file_exists() returns false in my death scene script.

In my score.gd:

extends Node

var score = 0
@onready var score_label = $Score

func add_point():
	score += 1
	score_label.text = "Score:" + str(score)

func save_score():
	var score_file = FileAccess.open("user://score.save", FileAccess.WRITE_READ)
	score_file.store_string(score)
	score_file.close()
	

When I put this in my death_scene.gd :

var file = FileAccess.file_exists("user://score.save")
print(file)

I get false in my output terminal.

In my current death_scene.gd:

extends Control
@onready var death_score = $Score2
@onready var high_score = $HighScore2

func _ready():
	loading_score()
# Called when the node enters the scene tree for the first time.
func loading_score():
	var score_file = FileAccess.open("user://score.save", FileAccess.READ)
	if FileAccess.file_exists(score_file) :
		death_score = score_file.get_string()
	```

The death_scene script returns this error message:

Invalid type in static function 'file_exists" in type 'FileAccess'. Cannot convert from argument 1 from Object to String.

Note that my death_scene is a separate scene that's not a child node of the game node . My score node on the other hand is a child node under my game node.

I'm not sure how to display my score after a game ends.

You are using this function incorrectly. This should be used to test a path, not a file itself.

Just. Check the file is not null.

1 Like

You probably want FileAccess.WRITE as you do not read the file while open in this function. Only writing save data.

store_string is hard to retrieve as get_string doesn’t exist for FileAccess; You either want store_pascal_string or store_line, both have a respective get_ function. but you are storing a number, so store_32 sounds better.

As @pennyloafers mentioned, wrong type for file_exists takes a file path. This code should check for the file existance before opening it too.

if FileAccess.file_exists("user://score.save"):
    var file := FileAccess.open("user://score.save", FileAccess.READ)
    death_score = file.get_32() # or file.get_pascal_string()
else:
    print("No save file found")
2 Likes