Hi,
Thanks for reading the book!
Unfortunately, Legion (the ECS) is responsible for the World
access (which is what the read_component
is handling) - and doesn’t flag that one at compile time. I really wish it did!
The issue can be caught by changing the if let
. if let
is like a single-case match
, so it’s only running the enclosed code if get_component_mut
succeeds - and continues on its way if it fails.
get_component_mut
returns a Result
type. So you have a few options for handling this:
The simplest way, not very specific:
if let Ok(mut health) = ecs.entry_mut(*victim).unwrap().get_component_mut::<Health>() {
} else {
// Print an error here
}
Using match
:
match ecs.entry_mut(*victim).unwrap().get_component_mut::<Health>() {
Ok(mut health) => { // do the health deduction }
Err(msg) => { // Handle the error, msg will tell you what went wrong }
}
Or you can choose to crash when things go wrong (surprisingly helpful for debugging):
let mut victim = ecs.entry_mut(*victim).unwrap().get_component_mut::<Health>().unwrap();
// Health deduction code
Hope that helps!