#Save file didnt work after closing window

21 messages · Page 1 of 1 (latest)

rancid crescent
#

So i want to save a best score everytime the player managed to get a score > best_score. The problem is that everytime i close the window of the running project it seems like the best_score got a reset and not saving it.

SaveFile.gd:


const SAVE_FILE = "user://save_file.save"
var best_score : int


func _ready():
    load_game()


func save_game():
    var file = FileAccess.open(SAVE_FILE, FileAccess.WRITE)
    file.store_var(best_score)
    file.close()


func load_game():
    if FileAccess.file_exists(SAVE_FILE):
        var file = FileAccess.open(SAVE_FILE, FileAccess.READ)
        best_score = file.get_var(best_score)
    else:
        best_score = 0```

GameManager.gd:
```extends Node

signal game_started
signal point_scored
signal bird_crashed

var is_game_started : bool = false
var is_game_ended : bool = false
var score : int = 0
var best_score


func _ready():
    game_started.connect(_on_game_started)
    point_scored.connect(_on_point_scored)
    bird_crashed.connect(_on_bird_crashed)


func _on_game_started():
    is_game_started = true
    is_game_ended = false
    
    score = 0
    best_score = SaveFile.best_score


func _on_point_scored():
    score += 1


func _on_bird_crashed():
    is_game_ended = true
    
    if score > best_score:
        best_score = score
        SaveFile.save_game()
        print(best_score)```

It shouldve not print the best score `if score > best_score: print(best_score)` (if for example i have scored 2 point while in my last run of the game i scored 5 point), but it still printing the best score
#

Can someone point out what and where did i do wrong?

soft ravine
dire bloom
#

you never seem to call load_game. so the best_score variale will keep its default of 0

rancid crescent
dire bloom
#

ok then maybe print the score after loading it so we can se if that works

soft ravine
#

thats what i did to save things

#

and load

dire bloom
#

so it prints 0 after loading

rancid crescent
dire bloom
#

ah..

#

you don't assign it to the autoload before saving

#

maybe its better to not have two variables

#
if score > best_score:
        best_score = score  #<--- this only changes the local variable, the autoload's copy is still as is
        SaveFile.save_game()
        print(best_score)
#

so maybe don't have a local copy of best_score and rather just work with the autoload

#

e.g

if score > SaveFile.best_score:
        SaveFile.best_score = score
        SaveFile.save_game()
        print(best_score)
rancid crescent
#

didnt realize that it only changes the local variable