get_tree().change_scene() is overwriting my global variables

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

I have this function:

func _on_PlayAgain_pressed():
	print("PLAYERS:", Global.Player1, " ", Global.Player2)
	get_tree().reload_current_scene()
pass

The print outputs the player objects, and then on the same reloaded scene script I have:

var Player1 = Global.Player1
var Player2 = Global.Player2 

Which prints null for both.

I don’t have any other function inbetween these two pieces of code.

I tried to change scene instead of reloading and the outcome is the same.

My global script has the following piece of code:

var Player1 : KinematicBody2D = null
var Player2 : KinematicBody2D = null

Maybe it is reloading the global script? Is this the expected behavior? I thought that global values should last between scenes.

:bust_in_silhouette: Reply From: rousbound

The problem was that when you add the global variable to the tree, when you delete the scene you are in, the object gets deleted too. The solution is to duplicate the object when assigning the global variable as in:

var Player1 = Global.Player1.duplicate()
var Player2 = Global.Player2.duplicate()
add_child(Player1)
add_child(Player2)

In this way, only the copy will get deleted