It looks functional enough but there are some potential issues.
Just looking at the save_highscore function for instance: Your code doesn’t check if the file was successfully opened. It’s a good practice to add error handling. While setting file = null will work, it’s better to be more explicit with file.close(). The FileAccess.WRITE_READ mode is used, but if you’re only writing, FileAccess.WRITE could be more appropriate.
func save_highscore():
var file = FileAccess.open(SAVEFILE, FileAccess.WRITE)
if file:
file.store_32(high_score)
file.close()
else:
print("Failed to open file for writing: ", SAVEFILE)
Hope that helps.
PS It is also a good idea to check the file exists before trying to open it too. Something like:
func save_highscore():
if FileAccess.file_exists(SAVEFILE):
var file = FileAccess.open(SAVEFILE, FileAccess.WRITE)
if file:
file.store_32(high_score)
file.close()
else:
# Handle failed opening however you want
print("Failed to open file for writing: ", SAVEFILE)
else:
# Handle file not found however you want too
print("File does not exist: ", SAVEFILE)
You program will throw an error and stop working? I would need to check the docs to be precise though.
Well actually it seems that if the file is not found in WRITE_READ mode a file is created for you anyway. So I suppose your code is perfectly functional but to me it feels like bad practice. But in reality it would work fine. I wonder what would happen if it failed to write when trying to correct automatically for your missing file?
Edit:
I believe it would throw a runtime error in that circumstance. So potentially without this and in the circumstance that the users device could not create a file then your program would crash. The file variable would be null and the store_32 would be a fatal error.
Alright thanks, I’m a little nervous to change anything now, and I haven’t had any problems (yet), but if something comes up I might have to change it. I just wanted to make sure nobody could like hack the program or something, because I think I heard that could happen with some save systems.
Oh yes you can. You access the file and change the value externally of course. It is not encrypted and although you might need a hex editor, it is not ‘secure’. Not that anyone would go to the effort for just a local game high score (presuming that is what you are using it for).
The only circumstance I can reasonably see your code having issues is if the users system memory is full! This is highly unlikely TBH.
PS In my own game, I have the file checks but generally I just ignore it if it does not save. The user would be upset coming back later to see their game didn’t actually save, but TBH and like you, I have never had this problem reported.