How do i remove a child, if it´s different each call?

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

Hello i save the levels of my game as different scenes.

Now i´m working on a function, that should remove the last level-scene from the tree and add the next one.

now i´m here:

func new_level():
    if G.on_target == G.boxes:
        G.pushes = 0
        in_game.remove_child() #what goes into the brackets here?
        G.level += 1
        var file = File.new()
        
        if file.file_exists("res://scenes/levels/Level_" + str(G.level) + ".tscn"):
            level = load("res://scenes/levels/Level_" + str(G.level) + ".tscn").instance()
            in_game.add_child(level)
        else:
            G.level -= 1
            win()

G.-variables are in my globals-script, that can be accessed from every other script in the game.
what can i insert into the brackets of

in_game.remove_child()

that uses the G.level from the globals-script to find the actual level-scene?

:bust_in_silhouette: Reply From: jgodfrey

Since you’re already using a singleton to manage various global properties, why not just store your current level object there too. That way, you can easily remove it when necessary.

So, right after you call add_child(), store that object away in your G singleton.

G.current_level = level

Then, if that variable has a value, use it to remove the current level:

if G.current_level:
    in_game.remove_child(G.current_level)

You’ll also want to add that variable to your G singleton. So, something like this, in the G.gd script.

var current_level = null

jgodfrey | 2022-03-27 21:19

Thanks, this works.

Drachenbauer | 2022-03-28 17:07

Great - glad it works for you.

Unrelated, but I’d recommend that you construct that scene string name only once. Not only is it more efficient, but it’s easier to update should the scene name format change in the future. So, something like this:

var next_scene = "res://scenes/levels/Level_" + str(G.level) + ".tscn"
if file.file_exists(next_scene):
    level = load(next_scene).instance()

jgodfrey | 2022-03-28 17:16