Dynamically changing the material of an entity #16787
-
I am trying to dynamically change the material of an entity via an event (websocket in my case). I am able to retrieve the IDs of my different materials and meshes (I am basing this on the glTF specification). I can retrieve the material assets via the Problem: The first modification is performed perfectly ✅ . However, the second one seems to remove the previous materials ❌ . Do you have any debugging tips, or where could this be coming from? fn refresh_mesh_primitive(world: &mut World, mesh_primitive: &MeshPrimitive) {
let mut material_assets = world.resource_mut::<Assets<StandardMaterial>>();
let mesh_primitive_material_asset = if let Some(material_id) = mesh_primitive.material {
let uuid: uuid::Uuid = material_id.into();
let asset_id = AssetId::from(uuid);
material_assets.get_strong_handle(asset_id).unwrap()
};
let entities_to_update: Vec<Entity> = {
let mut query = world.query::<(Entity, &MeshPrimitiveId)>();
query
.iter(world)
.filter(|(_, mesh_primitive_id)| mesh_primitive_id.0 == mesh_primitive.id)
.map(|(entity, _)| entity)
.collect::<Vec<_>>()
};
let mut commands = world.commands();
for entity in entities_to_update {
commands
.entity(entity)
.insert(mesh_primitive_material_asset.clone());
}
} Here is a video of two modifications (the first one works, the second does not)
Screen.Recording.2024-12-12.at.17.31.29.mp4 |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Note: when the same material is inserted twice into an entity, it disappears from view (the second time). commands
.entity(entity)
.insert(mesh_primitive_material_asset.clone()); |
Beta Was this translation helpful? Give feedback.
I understood why there's this behavior, because Assets.get_strong_handle upgrades the ID (and in my case changes the UUID) to another one, consequently, the indexing in Bevy is no longer correct.
However, I don't see how to use Assets.get to insert it into the entity, because the
get
method returnsOption<&A>
, which is a reference.Solution
Actually, I understood that I can use the ID directly instead of retrieving the assets, and everything works perfectly ✅