Trait godot::obj::WithBaseField

pub trait WithBaseField: GodotClass<Declarer = DeclUser> + Bounds {
    // Required methods
    fn to_gd(&self) -> Gd<Self>;
    fn base_field(&self) -> &Base<Self::Base>;

    // Provided methods
    fn base(&self) -> BaseRef<'_, Self> { ... }
    fn base_mut(&mut self) -> BaseMut<'_, Self> { ... }
}
Expand description

Trait that’s implemented for user-defined classes that provide a Base<T> field.

Gives direct access to the containing Gd<Self> from Self.

Required Methods§

fn to_gd(&self) -> Gd<Self>

Returns the Gd pointer containing this object.

This is intended to be stored or passed to engine methods. You cannot call bind() or bind_mut() on it, while the method calling to_gd() is still running; that would lead to a double borrow panic.

fn base_field(&self) -> &Base<Self::Base>

Returns a reference to the Base stored by this object.

Provided Methods§

fn base(&self) -> BaseRef<'_, Self>

Returns a shared reference suitable for calling engine methods on this object.

§Examples
use godot::prelude::*;

#[derive(GodotClass)]
#[class(init, base = Node)]
struct MyClass {
    base: Base<Node>,
}

#[godot_api]
impl INode for MyClass {
    fn process(&mut self, _delta: f64) {
        let name = self.base().get_name();
        godot_print!("name is {name}");
    }
}

However, we cannot call methods that require &mut Base, such as Node::add_child().

use godot::prelude::*;

#[derive(GodotClass)]
#[class(init, base = Node)]
struct MyClass {
    ///     base: Base<Node>,
}

#[godot_api]
impl INode for MyClass {
    fn process(&mut self, _delta: f64) {
        let node = Node::new_alloc();
        // fails because `add_child` requires a mutable reference.
        self.base().add_child(node);
    }
}

For this, use base_mut() instead.

fn base_mut(&mut self) -> BaseMut<'_, Self>

Returns a mutable reference suitable for calling engine methods on this object.

This method will allow you to call back into the same object from Godot, unlike what would happen if you used to_gd().

§Examples
use godot::prelude::*;

#[derive(GodotClass)]
#[class(init, base = Node)]
struct MyClass {
    base: Base<Node>,
}

#[godot_api]
impl INode for MyClass {
    fn process(&mut self, _delta: f64) {
        let node = Node::new_alloc();
        self.base_mut().add_child(node);
    }
}

We can call back into self through Godot:

use godot::prelude::*;

#[derive(GodotClass)]
#[class(init, base = Node)]
struct MyClass {
    base: Base<Node>,
}

#[godot_api]
impl INode for MyClass {
    fn process(&mut self, _delta: f64) {
        self.base_mut().call("other_method".into(), &[]);
    }
}

#[godot_api]
impl MyClass {
    #[func]
    fn other_method(&mut self) {}
}

Object Safety§

This trait is not object safe.

Implementors§