bevy - 获取实体的所有组件

标签 bevy

是否可以通过在 bevy rust 中包含实体来获取组件列表?例如用于调试目的。

use bevy::prelude::*;
fn main()
{
    App::build()
        .add_plugins(DefaultPlugins)
        .add_startup_system(setup.system())
        .add_system(first.system())
        .add_system(first_no_second.system())
        .add_system(first_and_second.system())
        .run()
}

fn setup(mut commands: Commands)
{
    commands.spawn().insert(FirstComponent(0.0));
    commands.spawn().insert(FirstComponent(1.0));
    commands.spawn().insert(SecondComponent::StateA);
    commands.spawn().insert(SecondComponent::StateB);
    commands.spawn().insert(SecondComponent::StateA).insert(FirstComponent(3.0));
    commands.spawn().insert(SecondComponent::StateB).insert(FirstComponent(4.0));
}

#[derive(Debug)]
struct FirstComponent(f32);

#[derive(Debug)]
enum SecondComponent
{
    StateA,
    StateB
}

fn first(query: Query<&FirstComponent>)
{
    for entity in query.iter()
    {
        println!("First: {:?}", entity)
    }
}

fn first_no_second(query: Query<&FirstComponent, Without<SecondComponent>>)
{
    for entity in query.iter()
    {
        println!("First without Second: {:?}", entity)
    }
}

fn first_and_second(query: Query<&FirstComponent, With<SecondComponent>>)
{
    for entity in query.iter()
    {
        println!("First with Second: {:?}", entity)
    }
}

bevy的ecs是如何理解某个Queue需要启动哪些系统的。在世界中,组件以某种方式与实体相关,对吗?是否有可能以某种方式从外部追踪这种联系?我真的很喜欢它的工作方式,对我来说它看起来很神奇,但我想了解“幕后”发生了什么

最佳答案

我发现仅通过 AppBuilder 就可以直接访问世界、组件和实体。以下是足以满足我的目的的示例代码

use bevy::prelude::*;
use bevy::ecs::component::{ComponentId, ComponentInfo};


fn main()
{
    App::build()
        .add_plugin(WorldPlugin::default())
        .run()
}

// some components for test
struct TestComponent;
struct TestComponent2;


#[derive(Default)]
struct WorldPlugin {}

impl Plugin for WorldPlugin
{
    fn build(&self, app: &mut AppBuilder)
    {
        // creating an entity with both test components
        let entity = app.world_mut()
            .spawn()
            .insert(TestComponent)
            .insert(TestComponent2)
            .id();
        // to interact with components and entities you need access to the world
        let world = app.world();
        // components are stored covertly as component id
        for component_id in get_components_ids(world, &entity).unwrap()
        {
            let component_info = component_id_to_component_info(world, component_id).unwrap();
            println!("{}", extract_component_name(component_info));
        }

    }
}


/// gets an iterator component id from the world corresponding to your entity
fn get_components_ids<'a>(world: &'a World, entity: &Entity) -> Option<impl Iterator<Item=ComponentId> + 'a>
{
    // components and entities are linked through archetypes
    for archetype in world.archetypes().iter()
    {
        if archetype.entities().contains(entity) { return Some(archetype.components()) }
    }
    None
}

fn component_id_to_component_info(world: &World, component_id: ComponentId) -> Option<&ComponentInfo>
{
    let components = world.components();
    components.get_info(component_id)
}

fn extract_component_name(component_info: &ComponentInfo) -> &str
{
    component_info.name()
}

此代码可以为您的实体获取一组组件,从而允许您获取有关组件的任何数据。这是从 bevy 源代码中获取的 ComponentInfo 结构的描述

#[derive(Debug)]
pub struct ComponentInfo {
    name: String,
    id: ComponentId,
    type_id: Option<TypeId>,
    // SAFETY: This must remain private. It must only be set to "true" if this component is
    // actually Send + Sync
    is_send_and_sync: bool,
    layout: Layout,
    drop: unsafe fn(*mut u8),
    storage_type: StorageType,
}

世界存储了一组组件、实体,“原型(prototype)”用于链接它们。下面附上示例图。 Short diagram

关于bevy - 获取实体的所有组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67457909/

相关文章:

rust - 如何更改 SpriteComponent 颜色?

rust - 如何在 Bevy 中翻转 spritesheet

rust - 我是否需要担心将Z轴用作上/下的任何问题?

bevy - 从 Bevy 中获取图像的宽度和高度

bevy - TextureAtlas Sprite 索引是否反射(reflect)了它们的添加顺序?

audio - 如何使用Bevy加载文件夹中的所有音频文件?

rust - 在Bevy游戏引擎中将1000x1000像素纹理分配给Sprite Sheet Bundle大约需要5秒

rust - 没有多个按钮系统的多个按钮?

rust - 如何将子代生成到现有组件中?