0 votes

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?

Godot version 3.5
in Engine by (16 points)
edited by

1 Answer

0 votes

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.
by (16 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 Frequently asked questions and 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 [email protected] with your username.