extends Resource
class_name SaveGame
const SAVE_GAME_PATH := "user://savegame.tres"
@export var health := 10
func write_savegame():
ResourceSaver.save(self, SAVE_GAME_PATH)
func load_savegame():
if ResourceLoader.exists(SAVE_GAME_PATH):
return ResourceLoader.load(SAVE_GAME_PATH)
else:
print("No save")
I have 4 buttons. Two that add and minus health. Two that save and load.
The health buttons and save button work. My struggle is with the load button.
When I press load the first time, it works fine. The health inside the save file gets loaded. But after the first load, it doesn’t work anymore. I change the health and when I press load, only the changed health gets printed. When I save again, the new health gets saved.
I thought this was supposed to work. Thank you for any help you give.
Im not sure you understood it correctly. So your problem is that when you load your save-file it works, but when you change the health and then load(before you save) it goes back to the old value? Thats how its supposed to work. When you load the savefile it only loads the values that you saved
I’m 100% sure I don’t understand something in the code. This is what I did:
1.run the scene
2. change health
3. press load button
4. it loads the saved values from the savefile
5. change health again
6. try to load from the save file again
7. second time loading doesn’t work, this is where I’m stuck
what exactly “doesnt work”? Do you get an error? Do you think you get the wrong values? You load the same savefile from before so the values should be back to the first time you saved
The first time I press the button to load. It correctly loads the value in the save file. The default value is 10. And when I press load, it changes to 25 from the save file. Even if I change the value before loading. The output shows 25.
If I try to do load it a second time. The print output is the current value. Even though the save file value is 25. The output will be 55 or however much I changed the value. I can save 55 as the health value but I can’t load 25 from the save file a second time.
The problem is probably the cacheMode in the load-method of ResourceLoader. It tells the loader to use the cached version of the resource (your first loaded file):
Yes, that was it. Adding in (,“”, 0) fixed it. I’m gonna have to study up on this cachemode thing.
Just 15 seconds before, I also found a method to fix it myself. But that was just reassigning the value to a var and it would be too much typing for many values.