0 votes

I have two GDNative script attached to two nodes (parent and child). Is is possible for script to call a method in the other in game? and whats the best way to go about this.

Thanks for any help.

asked Apr 5 in Engine by gdmark (12 points)

1 Answer

+1 vote

You can do this the same way as you'd do in GDScript, just needs a bit more checks and boilerplate.

get_node("Child").foo(42)

Becomes this in C++:

Node *child_node = get_node("Child");
ERR_FAIL_COND(child_node == nullptr);
Array arguments;
arguments.append(42);
child_node->call("foo", arguments);

The added check is to prevent crashes. Indeed, in GDScript, calling functions on a null object results in the engine stopping the game and telling you what's wrong, but in C++ those things are less forgiving^^

Although, call(string) is a generic, slow call. There should be a way to actually call the C++ function which may run faster:

Node *child_node = get_node("Child");
ERR_FAIL_COND(child_node == nullptr);
ChildClass *child = child_node->cast_to<ChildClass>();
ERR_FAIL_COND(child == nullptr);
child->foo(42);

Where ChildClass is the C++ class of your child script.
I never tried this though, only deduced it from the API.

answered Apr 5 by Zylann (26,139 points)

I got it work. I'm new to GDNative, so this was killing me. Thank you so much!
Both of your approaches work and for the second approach the syntax is:

ChildClass *child = Object::cast_to(child_node);

for anyone else interested.

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.