Godot Version
4.1.2
Question
I’m trying to save my main level’s state when I enter a temporary mini-level (a shop), but I haven’t been able to get my state to be remembered. Possibly because Godot does memory management and/or parameter passing different to how I expect.
Note that this is temporary saving, not saving the game state as a saved game.
I change to/from the temporary scene using:
scene_tree.change_scene_to_file( new_scene )
I am attempting to save my enemies to a variable in a globally preloaded script:
var enemies : Array[Node]
Most attempts to actually place data into this array fail. I have tried:
First Attempt:
Globals.enemies = Globals.current_scene_node.get_node( "Enemies" ).get_children()
Whenever I needed to look at Globals.enemies
it was empty.
I assumed this was because the parent node and all its children were being cleaned up when the scene was being destroyed.
Second Attempt:
nodes = []
for n in Globals.current_scene_node.get_node( node_name ).get_children():
nodes.append( n )
n.get_parent().remove_child( n )
print( node_name, " contains ", nodes.size())
The print statement here confirms that the array is populated, but a similar print statement at the call site says the array is empty.
I assumed this was because nodes
was passed as a copy or copy-on-write reference or something?
Third Attempt
var nodes = []
for n in Globals.current_scene_node.get_node( node_name ).get_children():
nodes.append( n )
n.get_parent().remove_child( n )
print( node_name, " contains ", nodes.size())
return nodes
Again, print inside the function showed the nodes array was populated, but the value the function returns at the call site is an empty array.
I assumed this was because nodes
gets destroyed or something?
Final Attempt
set( new_value ):
enemies = []
for n in new_value:
enemies.append( n )
n.get_parent().remove_child( n )
print( "enemies contains ", enemies.size())
This seems to have worked somewhat but I can’t get the values back out using:
var node : Node = Globals.current_scene_node.get_node( node_name )
for n in nodes:
print( "Adding ", n )
node.add_child( n )
I see all the Adding ...
lines appear in the console, but node
remains childless.
So, I’m guessing I’m missing a fundamental piece of information about function arguments and/or memory management or something.
Any explanations on why the above failed and how to fix things would be greatly appreciated. As would responses on the Right Way™ to do this.
Thanks,
Brian.