0 votes

I'm just getting started with Godot and it's awesome so far! The only gripe I have is that it seems it would be quite easy to call GetNode with an invalid node name or path.

I'm usually a typescript developer so I may be missing something in c# here but it seems that GetNode doesn't return a possibly null type when it can definitely fail to find a node and return null at runtime. It seems to me that this pattern of untyped access pushes a lot of potential crashes to runtime when the inevitable typo results in not getting the node you want.

Is there a way to have type safety with node names and paths?

asked Jun 30 in Engine by imagio (16 points)

1 Answer

0 votes

You can use getnodeor_null. In C# you have to tell it which node type to return GetNodeOrNull<Node type>("Path");
https://docs.godotengine.org/en/stable/getting_started/scripting/c_sharp/c_sharp_features.html

answered Jul 1 by Magso (2,667 points)

That could help a bit by giving runtime safety but it would be much nicer if there was a way to check the node names/paths statically. If for example the editor exported an enum of all the node names you could reference instead of just using strings. The issue I see is that it's very easy to move or rename a node which will break any code using GetNode -- you have to remember to update that manually in every place it's used. It would be much nicer if the compiler could warn of all the places where you referenced the now renamed or moved node.

I know what you mean, another way to get a node is using find node or using get_tree().get_nodes_in_group() then get node[0] from that array.

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 How to use this Q&A? before posting your first questions.