0 votes

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")


func load_game():
    var file = File.new()
    if not file.file_exists("user://saved_game.sav"):
        print("no file saved")

    if file.open("user://saved_game.sav", File.READ) != 0:
        print("error opening file")

    var data = {}

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...?

func _input(event):
    if Input.is_mouse_button_pressed(BUTTON_LEFT):
        score += 1
        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...

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


in Engine by (23 points)

1 Answer

+1 vote

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
        global.save_game() # Everytime it adds 1 score, I save the game
by (1,330 points)

Finally, thanks!

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.