Global player variable freed after scene change

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

Im trying to make a 2D platformer game and have implemented a scene called witchwhich contains all info about the witch. The witch is the player you play as.

I want to keep the info about the witch when changing scene so i made it a global variableA global variable containing the info about the witch

So this works during a the first scen where i add the player to the game_stage scene like the image below showsadding the player to stage1

Things to note is that i have a GUI that updated the health mana etc about the player, which is updated when the scene is created and also when the players stats changes(heals, takes dmg , etc etc)

The thing is when i change scenes (done by a simple area2d and body_entered function), the stage2´s GUI tries initialize it using the global Witch variable which apparently is “previously freed instance”.

How would figuring out this ?

Thanks in advance
Links to images incase they dont work
Imgur: The magic of the Internet
Imgur: The magic of the Internet

:bust_in_silhouette: Reply From: Zylann

It doesn’t work because the instance of Witch.tscn was part of the scene tree when you changed the level. So it got deleted, and your global variable now references a “deleted instance”.

You should consider removing the witch from the scene tree before switching levels, and add it back afterwards.
Another approach is to just not store the entire witch node as a global variable, instead create a script “” containing only variables shared across all levels, and store information such as health or player_name in there.