How to reference a GDScript class in GDExtension?

Godot Version

4.2

Question

For example, I have a class A define in gdscript. Then, I want to write a class B in C++ with GDExtension. Class B has a member of type class A. How to reference class A in C++? Where is the header file?

I don’t believe there will be a header file for it. However, there are ways to manipulate it in C++. To create the class, you can create the object it inherits and use set_script. Alternatively, you can save it as a scene and load it when you need it.

Get and set can be used to get or set the properties of the object. This may be what you’re looking for if you’re trying to get the member of the GDScript class, although the members may need to be exported first. Call can be used to call a method. Methods can be called without being exported.

This may not work for inner classes.

In gdscript.cpp, ClassDB is used to instantiate a class using only the name of the class. It also has other useful and informative methods to get metadata stored for every available class. However, it won’t have information on inner classes.

Inner classes can be thought of as a sub-script to the script they’re defined in. Like a regular script, they modify the behavior of the objects they’ve been set to. Unlike regular scripts, they do not extend from any classes. When they’re created in GDScript, a RefCounted object is created and their script is set to the inner class. Rather than modifying the inner class, you’re modifying the RefCounted object in the same way that you would be modifying the object for a defined regular class. In GDExtension, the creation of the RefCounted object and script has to happen manually.

// Load the main script
Ref<GDScript> script = ResourceLoader::get_singleton()->load("path_to_script");
// Get the inner class
Ref<GDScript> inner_class = script->get_script_constant_map()["name_of_inner_class"];
// Create RefCounted
Ref<RefCounted> rf;
// Instantiate RefCounted
rf.instantiate();
// Set the script of the RefCounted to the inner class
rf->set_script(inner_class);
// Use call/get/set/etc on RefCounted to manipulate it
UtilityFunctions::print(rf->get("property_in_inner_class"));
rf->call("method_in_inner_class");
rf->set("property_in_inner_class", "property_value");
1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.