0 votes

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.

Godot version 3.3.2
in Engine by (25 points)

1 Answer

0 votes

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

by (25 points)
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.