I would not be able to save it in the same file without deleting previous save file
I think it's okay overwrite the previous save file, so long as you read from it first.
scorePay = file.get_var(scorePay)
doorPay = file.get_var(doorPay)
gamePay = file.get_var(gamePay)
This doesn't look right. get_var takes a bool https://docs.godotengine.org/en/stable/classes/class_fileaccess.html#class-fileaccess-method-get-var
I'd recommend storing as JSON for easier debugging.
My personal style of doing this would be to create a PayState class that is only concerned with converting to/from JSON:
class PayState extends RefCounted:
var scorePay: int
var doorPay: int
var gamePay: int
static func createDefault() -> PayState:
var state = PayState.new()
state.scorePay = 1000
state.doorPay = 1000
state.gamePay = 2000
return state
static func fromJson(jsonStr: String) -> PayState:
var state = PayState.new()
var parser := JSON.new()
var parseResult := parser.parse(jsonStr)
if parseResult != OK:
push_error(("JSON Parse Error: %s\nin str %s\nat line %s" % [parser.get_error_message(), jsonStr, parser.get_error_line()]))
return null
var data = parser.data
if typeof(data) != TYPE_DICTIONARY:
push_error('data not a dictionary')
return null
var dict = data as Dictionary
if typeof(dict.get('scorePay')) != TYPE_INT:
push_error('scorePay not an int')
return null
if typeof(dict.get('doorPay')) != TYPE_INT:
push_error('doorPay not an int')
return null
if typeof(dict.get('gamePay')) != TYPE_INT:
push_error('gamePay not an int')
return null
state.doorPay = dict.get('doorPay')
state.scorePay = dict.get('scorePay')
state.gamePay = dict.get('gamePay')
return state
func toJson() -> String:
var json = {
'scorePay': scorePay,
'doorPay': doorPay,
'gamePay': gamePay,
}
return JSON.stringify(json)
func _to_string() -> String:
return toJson()
Then I would use it like this:
const savedFile = "user://SAVE_PAY.save"
var payState: PayState = null
func _enter_tree() -> void:
payState = readOrDefault()
func readOrDefault() -> PayState:
if not FileAccess.file_exists(savedFile):
return PayState.createDefault()
var file := FileAccess.open(savedFile, FileAccess.READ)
var jsonStr := file.get_line()
var state := PayState.fromJson(jsonStr)
if state == null:
return PayState.createDefault()
return state
func write():
assert(payState != null)
var file := FileAccess.open(savedFile, FileAccess.WRITE)
file.store_line(payState.toJson())
That fromJson() is pretty strict, requiring all parameters. If some are optional, you could do like this:
if typeof(dict.get('scorePay')) != TYPE_INT:
push_warning('scorePay not an int, defaulting to 1000')
state.doorPay = 1000
else:
state.doorPay = dict.get('doorPay')