The Godot Q&A is currently undergoing maintenance!

Your ability to ask and answer questions is temporarily disabled. You can browse existing threads in read-only mode.

We are working on bringing this community platform back to its full functionality, stay tuned for updates. | Twitter

+3 votes

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

in Engine by (85 points)

Call a script function or just get the node?

Second variant.

1 Answer

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

by (29,360 points)
selected by

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


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 Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.