0 votes

I have a scene with a node and a script attached, this node instances other scenes procedurally. The first time it runs, it adds the children correctly.

Whenever I call GetTree().ReloadCurrentScene(), I would expect everything to get cleaned up (i'm assuming nodes get destroyed and the scene gets added again), but something goes wrong, and AddChild(node) does absolutely nothing.

Digging around (i'm using vscode) I noticed the object i'm trying to add a child to is disposed, but that's impossible (unless i'm missing something) because the node should've been destroyed and cleaned up, and the moment the scene gets reloaded again it should have re-run the scripts from the beginning creating a new instance, as if I were to run the game again!(?)

How would I get around this? Should I Add/Remove nodes manually one by one?

From the vscode debug inspector, this is the node I should add a child to after I reload the scene:
enter image description here

I also found a similar question here but no one has given a proper answer there yet.

Godot version 4.0 beta 4
in Engine by (54 points)

1 Answer

0 votes
Best answer

I realized my mistake. This is not an Issue with godot but my C# code. The node I have was a pseudo-singleton holding its own reference for static access. Since the call to add a child was from another class, it was looking for the instance which has been disposed.

I made it a normal class, added the node to a group, and replaced every .GetInstance() method call with a custom Utils call function I have, and now it works properly; for those interested:

static SceneTree GetMainLoopAsSceneTree() {
    return Engine.GetMainLoop() as SceneTree;
}

public static T GetFirstNodeInGroupOfType<T>(string group) where T : class {
    foreach (Node node in GetMainLoopAsSceneTree().GetNodesInGroup(group)) {
        if (node.GetType().IsAssignableFrom(typeof(T))) {
            return node as T;
        }
    }

    return null;
}
by (54 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.