Saving Data Breaks Mobile Game

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By PickledPenguin

After what seems like an eternity, I finally finished my mobile game and it works great in the editor! And when I exported it to my phone (iphone SE) the first time, it also worked! Yay! However, when I added in the code to save the game’s data, it wouldn’t work when I exported it to my phone, even though it still worked perfectly in the editor!

I have a menu system set up that works just fine until you click the button that changes the scene to the game scene. The button seems to do nothing at all and doesn’t switch to the game. So I exported the project with the actual game scene being the main scene, which resulted in the app not loading. I think that this means that the way I’m saving the data is messing with the game and making it not load on mobile for some reason.

Here’s how I’m saving the number of coins the player has:

extends Node

var total_coins_file = "user://total_coins_file.save" 

var total_coins: = 0 setget set_total_coins

signal coins_updated

func _ready() -> void:
    load_total_coins()
func set_total_coins(value):
    total_coins = value
    emit_signal("coins_updated")
    save_total_coins()

func save_total_coins():
    var file = File.new()
    file.open(total_coins_file, File.WRITE)
    file.store_var(total_coins)
    file.close()
func load_total_coins():
    var file = File.new()
    file.open(total_coins_file, File.READ)
    total_coins = file.get_var(total_coins)
    file.close()

I’m using a few more of these save/load functions to save other data like what the player has bought with their coins at the shop and what the player has equipped. I thought about using a dictinoary, but this seemed more straightforward and easier to debug.

To be clear, the game worked fine until I added these functions, so they must have the problem.

I would be extreamly grateful for any help, I have been stressing over this for the past few days and can’t find out what’s wrong. Thank you!

:bust_in_silhouette: Reply From: FrazzleTime

Have you tried checking if a save file exists before loading or saving?

var savegame = File.new()
if !savegame.file_exists(save_file_path): 
	#create save if it doesn't exist
	save_data = { "coins":0}
	saveData(save_file_path, save_data)
else:
	#use current save
	save_data = loadData(save_file_path)

func loadData(path):
var f = File.new()
if f.file_exists(path):
	f.open(path, File.READ)
	var data = f.get_var()
	f.close()
	return data
return null