gdrust_export_node_path_macro
Reduces boilerplate code when acquiring references through NodePath.
Usage consists of (full example on a few paragraphs bellow):
- Replacing
#[derive(NativeClass, Default)] #[inherit(Node)]with#[extends(Node)] - Removing the
NodePathfields marked with#[property] - Placing
#[export_path]behind the fields you wish to acquire throughNodePath - Removing your implementation of
fn new(&mut self, _owner: &Node) - Manually call
self.grab_nodes_by_path(_owner);on your_ready()declaration
The #[extends] attribute macro:
- Replaces itself with
#[derive(NativeClass)] #[inherit(Node)] - Then, for each field marked with
#[export_path]:- Declares another field of similar name but with a
path_prefix andNodePathas type, as well as a regular#[property]attribute. (Vec<Ref<Node>>uses aVec<NodePath>type instead) - Example input/output:
#[export_path] node: Option<Ref<Node>>/#[property] path_node: NodePath, node: Option<Ref<Node>>,
- Declares another field of similar name but with a
- Declares a impl block with two functions:
fn grab_nodes_by_path(&mut self, _owner: &Node) { // searches for all the nodes/instances from the NodePath fields generated, assigning each to their original field in self }fn new(_owner: &Node) -> Self { Self::default() }
Supports exporting:
Option<Ref<T>>where T is a Godot's built-in type that inheritsNode(such as:Node2D,Control,ProgressBar,KinematicBody, ...)Vec<Ref<T>>where T is a Godot's built-in type that inheritsNodeOption<Instance<T>>where T is a custom native script defined by you, as long as the script inherits a Godot's built-in type that inheritsNodeVec<Instance<T>>where T is a custom native script defined by you, as long as the script inherits a Godot's built-in type that inheritsNode
PS 1: Note that Vec<Ref<T>>/Vec<Instance<T>> uses Ref<T>/Instance<T> directly instead of Option<Ref<T>>/Option<Instance<T>>
PS 2: Not related to this crate, but to gdnative-rust itself: In the editor, Vec<NodePath> will be shown as an array of Variant, you have to click on each element of the array, chose NodePath, then you'll be able to drag nodes in.
The base of the implementation was taken from gdrust.
Usage
Replace
With
// you can replace Node with any other Godot built-in node type
Which expands to (manually formatted for readability)
Misc / Limitations
- You may still freely use the other
gdnativeattributes like#[register_with]#[no_constructor]#[user_data]#[property]. Just make sure to always place them bellow#[extends], except#[property]which still goes behind fields. grab_nodes_by_path(&mut self, owner: &Node)will panic if it fails to validate any of the exported paths.- You cannot define your own
Self::new(). _owneringrab_nodes_by_path(&mut self, owner: &Node)uses hardcoded&, so you cannot declareownerin_ready(&mut self, #[base] _owner: &Node)asowner: TRef<Node>.