Topic was automatically imported from the old Question2Answer platform.
Asked By
Criepstar
So I’m trying to save the highscore for my game but there’ s always a error at the function if the player dies:
if score > Signals.highScore:
Signals.highScore = score
save_data()
The error is ‘Invalid operands ‘int’ and ‘Nil’ in operator ‘>’’.
I even tried multiple tutorials and the godot documentation, but nothing worked
Here’s also the code for the saving and loading
var save_path = "res://savegame.save"
func save_data():
var file = File.new()
file.open(save_path, File.WRITE)
file.store_var(Signals.highScore)
file.close()
func load_data():
var file = File.new()
if file.file_exists(save_path):
file.open(save_path, File.READ)
Signals.highScore = file.get_var()
file.close()
print(Signals.highScore)
This has nothing to do with the save code. The error occurs in the comparison (very first line), where one of the operands isn’t a valid number (Nil). Maybe Signals.highScore doesn’t have a value yet when you execute this part of the code for the first time?
So i should set the value like 0?
Criepstar | 2020-12-16 12:51
While this would work, I’d rather try to load the previous highscore first, and only set it to 0 if this fails for whatever reason (file not found, invalid file content, …). Otherwise, you’ll always lose your previously saved highscore as soon as a new one is saved.
Thomas Karcher | 2020-12-16 13:26
Thank you for your help
Criepstar | 2020-12-16 13:38
Since at the end of the load, ready and highscore func print(Signals.highScore), I always get the output Null, I don’t know if its Null only in the german language(the language, the editor is in) in english its Zero. And it doesnt generate a save file. I made a if else at the load func. Have I made an mistake at the save function?
Criepstar | 2020-12-16 17:05
“Null” is not the same as “0”, but means “empty, not defined”. So the value wasn’t assigned yet when you tried to print it. To make sure highScore has a value from the beginning, try the following:
func load_data():
var file = File.new()
if file.file_exists(save_path):
file.open(save_path, File.READ)
Signals.highScore = file.get_var()
file.close()
# make sure to assign a default value in case anything went wrong before
if typeof(Signals.highScore) == TYPE_NIL:
Signals.highScore = 0
func _ready():
load_data()
print(Signals.highScore)
Now you should see “0” (or some other number, but not “Null”) in the output, and saving should work as well, correct?
By the way: Feel free to reply in German if that’s easier for you.
Thomas Karcher | 2020-12-16 20:25
Really, thank you for your help, now its working fine.