Is there a way to have static (enum) node names/paths instead of strings with c#?

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

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?

:bust_in_silhouette: Reply From: Magso

You can use get_node_or_null. In C# you have to tell it which node type to return GetNodeOrNull<Node type>("Path");

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.

imagio | 2020-07-01 14:14

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.

Magso | 2020-07-01 14:45