|
| 1 | +--- |
| 2 | +title: Entity Reference Counting |
| 3 | +authors: ["@andriyDev"] |
| 4 | +pull_requests: [] |
| 5 | +--- |
| 6 | + |
| 7 | +`Arc` is a common tool in a Rust programmer's toolbelt. It allows you to allocate data and then |
| 8 | +reference that data in multiple places. Most importantly, it drops the data once all references have |
| 9 | +been removed. |
| 10 | + |
| 11 | +We've recreated this tool for entities! With `EntityRc`, users can now reference an entity and have |
| 12 | +it automatically despawned when all `EntityRc`s have been dropped. |
| 13 | + |
| 14 | +To do this, first create an `EntityRcSource`, and store it somewhere (like a resource). |
| 15 | + |
| 16 | +```rust |
| 17 | +#[derive(Resource)] |
| 18 | +struct MyReferenceCountingThingy { |
| 19 | + order: u32, |
| 20 | + rc_source: EntityRcSource, |
| 21 | +} |
| 22 | + |
| 23 | +fn setup(mut commands: Commands) { |
| 24 | + commands.insert_resource(MyReferenceCountingThingy { |
| 25 | + order: 0, |
| 26 | + rc_source: EntityRcSource::new(), |
| 27 | + }); |
| 28 | +} |
| 29 | +``` |
| 30 | + |
| 31 | +Next, create a system to regularly handle any drops: |
| 32 | + |
| 33 | +```rust |
| 34 | +fn handle_drops(rc_thingy: Res<MyReferenceCountingThingy>, mut commands: Commands) { |
| 35 | + rc_thingy.handle_dropped_rcs(&mut commands); |
| 36 | +} |
| 37 | +``` |
| 38 | + |
| 39 | +Lastly, provide an interface for users to create `EntityRc`s: |
| 40 | + |
| 41 | +```rust |
| 42 | +#[derive(SystemParam)] |
| 43 | +pub struct CreateReferences<'w, 's> { |
| 44 | + rc_thingy: ResMut<'w, MyReferenceCountingThingy>, |
| 45 | + commands: Commands<'w, 's>, |
| 46 | +} |
| 47 | + |
| 48 | +// We expect most uses will wrap this reference-count in a wrapper that provides a more strict API. |
| 49 | +pub struct MyHandle(EntityRc<u32>); |
| 50 | + |
| 51 | +impl MyHandle { |
| 52 | + pub fn get_order(&self) -> u32 { |
| 53 | + *self.0 |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +impl CreateReferences { |
| 58 | + pub fn create_reference(&mut self) -> MyHandle { |
| 59 | + // Spawn an entity to be reference-counted. |
| 60 | + let entity = self.commands.spawn((Transform::from_xyz(10.0, 20.0, 30.0))).id(); |
| 61 | + self.rc_thingy.order += 1; |
| 62 | + // Store the order number in the `EntityRc` so it can be accessed from any handle. This can |
| 63 | + // store whatever you want! |
| 64 | + self.rc_thingy.rc_source.create_rc(entity, self.rc_thingy.order); |
| 65 | + } |
| 66 | +} |
| 67 | +``` |
| 68 | + |
| 69 | +This provides users with an API like: |
| 70 | + |
| 71 | +```rust |
| 72 | +fn user_system(mut refs: CreateReferences, mut commands: Commands) { |
| 73 | + let new_handle = refs.create_reference(); |
| 74 | + commands.spawn(HoldsAReference(new_handle)); |
| 75 | +} |
| 76 | +``` |
0 commit comments