+1 vote

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

asked Mar 1, 2017 in Engine by Kovalski (83 points)

Call a script function or just get the node?

Second variant.

1 Answer

+2 votes
Best answer

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

answered Mar 1, 2017 by Zylann (21,017 points)
selected Mar 2, 2017 by Kovalski

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.

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.