MrGVSV/bevy_proto

Question: How to spawn a simple cube

Occuros opened this issue · 0 comments

Bevy provides simple shapes to whitebox a level or to create simple gameplay prototypes.

Ideally I would like to use bevy_proto to define the locations and shapes for faster iterations, especially for colliders for rapier etc., but when I try to get the handle of the created mesh, it panicks.

Here is what I tried to do:

#[derive(Serialize, Deserialize)]
pub struct ShapeDef {
    pub size: f32,
    pub color: Color,
    pub position: Vec3,
    #[serde(skip)]
    pub mesh_handle:  RwLock<Option<Handle<Mesh>>>,
    #[serde(skip)]
    pub material_handle: RwLock<Option<Handle<StandardMaterial>>>,
}
#[typetag::serde]
impl ProtoComponent for ShapeDef {
    fn insert_self(&self, commands: &mut ProtoCommands, asset_server: &Res<AssetServer>) {

        let mesh_handle_id = self.mesh_handle.read().unwrap().as_ref().unwrap().id();
        let mesh_handle = commands.get_handle(self, mesh_handle_id).expect("mesh handle");
        let material_id = self.material_handle.read().unwrap().as_ref().unwrap().id();
        let material_handle = commands.get_handle(self, material_id).expect("material handle");
        commands.insert(PbrBundle {
            mesh: mesh_handle,
            material: material_handle,
            transform: Transform::from_xyz(self.position.x, self.position.y, self.position.z),
            ..default()
        });
    }

    fn prepare(&self, world: &mut World, prototype: &dyn Prototypical, data: &mut ProtoData) {
        let mut meshes = world.get_resource_mut::<Assets<Mesh>>().unwrap();

        let mesh_handle = meshes.add(Mesh::from(shape::Cube { size: self.size }));
        let mut materials = world.get_resource_mut::<Assets<StandardMaterial>>().unwrap();
        let material_handle = materials.add(Color::rgb(0.3, 0.5, 0.3).into());
        *self.mesh_handle.write().unwrap() = Some(mesh_handle);
        *self.material_handle.write().unwrap() = Some(material_handle);
    }
}

The panic happens when I try to extract the mesh_handle from the commands_get_handle().

How exactly can I pass the Handle<Mesh> from the prepare invocation to the insert_self.