How to use GetNode() for C# class not attached to a node in the scene tree

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

I’m attempting to access a tilemap node in the scene tree from a C# class that is not attached to a node. I have a MapGenerator class and I want to pull a reference to the tilemap so I can populate it procedurally. I can’t see a need to attach it to a node, even though it works fine that way, but I feel there should be a way to use it as a stand-alone class.

GetNode() fails to find the tilemap node.

I’ve tried…

GetTree().Root.GetNode("root/World/Tilemap_Walls);
GetTree().Root.GetNode("World").GetNode(Tilemap_Walls);

… and every variation possible (except the correct one maybe?)

The c# class works fine when attached to a node in the scene or if I pass the node reference in a parameter.

I’ve searched and searched all of the internets for a solution but I thought I would try here before I make a coding commitment.

GetTree() will be null unless the node is in the tree (that is, there’s no SceneTree until added to one). Is there a reason why it isn’t in the tree if it needs to interact with other nodes? For example, a game may have a ‘Map’ parent node with Tilemap nodes as children, where the parent node populates the children as appropriate (e.g. the enemies layer or walls). You could perhaps broadcast (like an event) the reference but this seems like asking for trouble.

spaceyjase | 2023-01-25 20:12

I’m developing a rather complex colony survival game and the original c++ concept code contains dozens of classes. The classes are mostly for intangibles such as atmosphere, resource data, etc. If I created a node for every script the scene tree would be bloated. I also find c-style code easier to read and maintain (my background) so just hammering out small, useful classes is kind of my thing.

I understand the lack of a scene tree if the script is not “instantiated” within it. I’ve been using Init() functions to pass node references and that’s working ok. It’s what I would have done in c++ so no big deal. GDscript will definitely spoil you. I started prototyping in Godot with the intention of porting to Unity, but as I’m sure most users have experienced, I’m now in an early alpha version with no intention of porting lol.

I consider this an answer to my question! Not sure how to turn your comment into an answer though.

Thanks for the help!!

Tar_Get() | 2023-01-25 23:52

:bust_in_silhouette: Reply From: Tar_Get()

Please see comment from spaceyjase for the answer…