Is my method for cleaning up old nodes a bad idea?

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

I am building an open world 2D game where the character is loaded into new scenes frequently. I noticed that previous nodes were still active in the tree after calling get_tree().change_scene("next_scene"). For example, the _physics_process(delta) function of a node that is no longer of interest is called continuously even after the game no longer needs the node. I am imagining this builds up over time and seems very process intensive.

To prevent this, I started calling queue_free() after the scene is changed, but I don’t want to remember this every time on the calling node. Instead, I wrote a global function in a singleton that takes in the calling node instance as a parameter and, after loading the player into the next relevant scene, it cleans up the old node (simplified version of the function below):

func change_player_location(next_location: String, call_node: Node):
	return get_tree().change_scene(next_location)

My goal is to not have to remember to clean up nodes. Should I be concerned about this? Is there a better way?

:bust_in_silhouette: Reply From: joshmcode

It seems like a clean way to do this is the _deferred_goto_scene(path) method, which is (I cannot remember where in the docs I came across this function, but I’m fairly certain it is detailed in the official docs somewhere):

func _deferred_goto_scene(path):
    var root = get_tree().get_root()
    current_scene = root.get_child(root.get_child_count() - 1)

    # It is now safe to remove the current scene

    # Load the new scene.
    var s = ResourceLoader.load(path)

    # Instance the new scene.
    current_scene = s.instance()

    # Add it to the active scene, as child of root.

    # Optionally, to make it compatible with the SceneTree.change_scene() API.