I’ve moved the file checks to the start of the function. You could do something like this, but it has inherent flaws:
func LoadSettings():
if not FileAccess.file_exists("user://.file"):
# Handle missing file
return
var file = FileAccess.open("user://.file", FileAccess.READ) # This can fail
if not file:
# Handle open error
return
# Here we know the file exists, and we could open it
languague = file.get_var(languague)
sensi = file.get_var(sensi)
fullscreen = file.get_var(fullscreen)
quality= file.get_var(quality)
sound = file.get_var(sound)
for item in [language, sensi, fullscreen, quality, sound]:
if not item:
# Handle null case, but which one failed?
FileAccess.get_var() will error and return null if it cannot return a valid Variant, however you don’t have an easy way to check which call failed without modifying the structure of the code a bit.
You could use ConfigFile for this, as gertkeno said, and that would be better. If you don’t want to, however, you should consider storing a single Dictionary inside the file, as opposed to multiple Variants.
enum Option {
LANGUAGE,
SENSI,
FULLSCREEN,
QUALITY,
SOUND,
}
# Default values. This is what you store with SaveSettings()
var option_value: Dictionary[Option, int] = {
Option.LANGUAGE: 0,
Option.SENSI: 50,
Option.FULLSCREEN: 1,
Option.QUALITY: 4,
Option.SOUND: 75,
}
func LoadSettings():
if not FileAccess.file_exists("user://.file"):
# Handle missing file
return
var file = FileAccess.open("user://.file", FileAccess.READ)
if not file:
# Handle open error
return
var variant: Variant = file.get_var()
if not variant is Dictionary:
# Handle unexpected file content
return
if not option_value.is_same_typed(variant):
# Handle unexpected Dictionary
return
for key: Option in option_value:
if variant.has(key):
option_value[key] = variant.get(key)
Yes, there are a lot of checks to do when working with files. You don’t have to store everything inside the dictionary as int, although that makes it easier to check. If you were to store Variant values, you will need additional checks to make sure you don’t get a String for SOUND from the file somehow.