0 votes

i have this code

func _on_sprite_pressed():
      Score += 1
      $ScoreLabel.text = str(Score) 

and everytime i change the scene the Score resets.

How can i remain the Score while changing Scenes?

in Engine by (137 points)
edited by

1 Answer

+4 votes
Best answer

Store the score value (and any other values that need to persist through scene changes) in an AutoLoad script.

To do that:

  • Create a new script to hold the values (say, Globals.gd)
  • Add the required variables to it. Something like:

    extends Node
    var Score = 0
  • Add the new script to the AutoLoad list via Project | Project Settings | AutoLoad (tab)

  • Now, in the scripts that need to reference the new, global variable, prefix the references with the name of your autoloaded script. In my example, that's Globals. So, to reference the contained Score variable, just use Globals.Score

For example, your above-posted script would be modified like this:

func _on_sprite_pressed():
      Globals.Score += 1
      $ScoreLabel.text = str(Globals.Score) 
by (16,802 points)
selected by
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 Frequently asked questions and 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 [email protected] with your username.