Save Game not working, some help would be nice.

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Kavi
:warning: Old Version Published before Godot 3 was released.

So I’ve been trying to learn how to save a game, keeping your highscore etc. I created a global gdscript with the node name global, this is the code I used inside the global.gd script. (Btw the score will be the highscore)

extends Node

var data = {
	score = 0
	}

func save_game():
	var file = File.new()
	if file.open("user://saved_game.sav", File.WRITE) != 0:
		print("error opening file")
		return
	
	file.store_line(data.to_json())
	file.close()

func load_game():
	var file = File.new()
	if not file.file_exists("user://saved_game.sav"):
		print("no file saved")
		return
	
	if file.open("user://saved_game.sav", File.READ) != 0:
		print("error opening file")
		return
	
	var data = {}
	data.parse_json(file.get_line())

Then I created two scenes, a main menu menu.tscn and a level, main.tscn I then used a control node as the main node of the main scene.
I created a script inside of the control node.

I’ve made a label and when I click it adds 1 score to the label, and everytime the label is clicked I do global.save_game() so I can save the exact score.

and In my _ready code I do global.load_game so when you switch from the menu to level 1, the code runs and loads your game, right? This is my code inside of the control node

extends Control

var score = 0

func _ready():
	load_game() # When the game is switched from the menu I load the score...?
	get_node("player/label").set_text(str(score))
	set_process_input(true)
	pass

func _input(event):
	if Input.is_mouse_button_pressed(BUTTON_LEFT):
		score += 1
		get_node("player/label").set_text(str(score))
		save_game() # Everytime it adds 1 score, I save the game
	
	if Input.is_key_pressed(KEY_0): # This is just to change back to the menu scene...
		get_tree().change_scene("res://Scenes/menu.tscn")

Can anyone help me?
Goal -Like a clicker game-

-Kavi

:bust_in_silhouette: Reply From: YeOldeDM

You have two different variables named data there. One is being set when you click, and the other (the one you’re saving/loading) is doing nothing.
What you need to do is have your mouse click action set the value in global.data.score

func _input(event):
    if Input.is_mouse_button_pressed(BUTTON_LEFT):
        global.data.score += 1
        get_node("player/label").set_text(str(global.data.score))
        global.save_game() # Everytime it adds 1 score, I save the game

Finally, thanks!

Kavi | 2017-04-15 23:16