UserSingleton

Trait UserSingleton 

pub trait UserSingleton: GodotClass<Declarer = DeclUser, Memory = MemManual> + Bounds { }
Expand description

Trait for user-defined singleton classes in Godot.

Implementing this trait allows accessing a registered singleton instance through singleton(). User singletons should be registered under their class name – otherwise some Godot components (for example GDScript before 4.4) might have trouble handling them, and the editor might crash when using T::singleton().

There should be only one instance of a given singleton class in the engine, valid as long as the library is loaded. Therefore, user singletons are limited to classes with manual memory management (ones not inheriting from RefCounted).

§Registration

Godot-rust provides a way to register given class as an Engine Singleton with #[class(singleton)].

Alternatively, user singleton can be registered manually:

#[derive(GodotClass)]
#[class(init, base = Object)]
struct MyEngineSingleton {}

// Provides blanket implementation allowing to use MyEngineSingleton::singleton().
// Ensures that `MyEngineSingleton` is a valid singleton (i.e., a non-refcounted GodotClass).
impl UserSingleton for MyEngineSingleton {}

struct MyExtension;

#[gdextension]
unsafe impl ExtensionLibrary for MyExtension {
    fn on_stage_init(stage: InitStage) {
        if matches!(stage, InitStage::MainLoop) {
            let obj = MyEngineSingleton::new_alloc();
            Engine::singleton()
                .register_singleton(&MyEngineSingleton::class_id().to_string_name(), &obj);
        }
    }

    fn on_stage_deinit(stage: InitStage) {
        if matches!(stage, InitStage::MainLoop) {
            let obj = MyEngineSingleton::singleton();
            Engine::singleton()
                .unregister_singleton(&MyEngineSingleton::class_id().to_string_name());
            obj.free();
        }
    }
}

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§