命令
可参考的官方例子:
ecs_guide
.
使用 Commands
来创建/销毁实体、现有实体上添加/删除组件、管理资源。
这些命令行为不会立即生效,它们被排在队列中,以便在接下来安全的时候执行。参见:阶段。
(如果你不使用阶段,这意味着你的其他 systems 将在下一帧更新时看到这些操作结果)。
fn spawn_player(
mut commands: Commands,
) {
// manage resources
commands.insert_resource(GoalsReached { main_goal: false, bonus: false });
commands.remove_resource::<MyResource>();
// create a new entity using `spawn`
let entity_id = commands.spawn()
// add a component
.insert(ComponentA)
// add a bundle
.insert_bundle(MyBundle::default())
// get the Entity ID
.id();
// shorthand for creating an entity with a bundle
commands.spawn_bundle(PlayerBundle {
name: PlayerName("Henry".into()),
xp: PlayerXp(1000),
health: Health {
hp: 100.0, extra: 20.0
},
_p: Player,
sprite: Default::default(),
});
// spawn another entity
// NOTE: tuples of arbitrary components are valid bundles
let other = commands.spawn_bundle((
ComponentA::default(),
ComponentB::default(),
ComponentC::default(),
)).id();
// add/remove components of an existing entity
commands.entity(entity_id)
.insert(ComponentB)
.remove::<ComponentA>()
.remove_bundle::<MyBundle>();
// despawn an entity
commands.entity(other).despawn();
}
fn make_all_players_hostile(
mut commands: Commands,
query: Query<Entity, With<Player>>,
) {
for entity in query.iter() {
// add an `Enemy` component to the entity
commands.entity(entity).insert(Enemy);
}
}