GDNative: Calling other GDNative functions?

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

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.

:bust_in_silhouette: Reply From: Zylann

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.

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.

gdmark | 2020-04-06 00:32