Remain Score While Changing Scenes

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

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?

:bust_in_silhouette: Reply From: jgodfrey

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