How do I create a UiWidget at runtime as an entity?

53 views Asked by At

Imagine I've created a container

let created = UiWidget::Container::<NoCustomUi, String, ()> {
    transform: UiTransformData::default(),
    background: None,
    children: Vec::new(),
};

How do I add it to the world and get its entity back? Something like:

let entity = world
    .create_entity()
    .with(container)
    .build();

But it says "the trait specs::world::comp::Component is not implemented for amethyst_ui::prefab::UiWidget<amethyst_ui::prefab::NoCustomUi, std::string::String>".

I'm using Amethyst v0.15

1

There are 1 answers

1
Francois Mockers On BEST ANSWER

UiWidget actually can't be added to an Entity directly, as it's meant to be loaded through the Prefab

You have to create UiTransform, UiText or one of the few other Struct from amethyst::ui that implements Component and add them to an Entity

let ui_transform = UiTransform::new(
    String::from("demo_text"),   // id
    Anchor::Middle,              // anchor
    Anchor::Middle,              // pivot
    0f32,                        // x
    0f32,                        // y
    0f32,                        // z
    100f32,                      // width
    30f32,                       // height
);

let ui_text = UiText::new(
    font_handle,                 // font
    String::from("Hello World"), // text
    [1.0, 1.0, 1.0, 0.5],        // color
    25f32,                       // font_size
    LineMode::Single,            // line mode
    Anchor::Middle,              // alignment
);

world.create_entity()
    .with(ui_transform)
    .with(ui_text)
    .build();

You can find more information on how to do that in the Amethyst book under the User Interface section.