C# - AddChild not working after GetTree().ReloadCurrentScene(); 'System.ObjectDisposedException'

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

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.

:bust_in_silhouette: Reply From: MEDBVLL

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;
}