0 votes

i have this code

func _on_sprite_pressed():
      Score += 1
      $ScoreLabel.text = str(Score) 
      get_tree().change_scene("res://Game.tscn")

and everytime i change the scene the Score resets.

How can i remain the Score while changing Scenes?

in Engine by (136 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) 
      get_tree().change_scene("res://Game.tscn")
by (12,286 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 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.