Calling nodes from C++

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Kovalski
:warning: Old Version Published before Godot 3 was released.

How can I call from C++ a node from scene?

Call a script function or just get the node?

Zylann | 2017-03-01 17:52

Second variant.

Kovalski | 2017-03-01 17:58

:bust_in_silhouette: Reply From: Zylann

In C++, getting a node works the same way as in GDScript. The main difference is, because you work at engine-level, types and potential errors have to be checked:

Node * node = get_node(NodePath("Hello"));
// If the node can be found
if(node != NULL) {
	Sprite * sprite = node->cast_to<Sprite>();
	// If the node is a Sprite
	if(sprite != NULL) {
		// Do stuff with sprite
	}
}

If you don’t check for NULLs and failed casts, you are likely to get crashes, so better avoid them if you know that can be broken by a wrong use of the editor/game data :wink:

I needed to add the c++ class explicitly as a child in the script, for example:

get_node("Node2D").add_child(c++_class_instance)

,
then use absolute paths in the c++ class , for example:

void c++_class::example_function(){ get_node("/root/Node2D")}

in order to get this to work.
Also the c++ class needs to be a subclass of Node2D or similar in order to use
get_node() like this.

rhythmpattern | 2017-06-26 08:43