You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bevy 0.11默认字体文本无法显示问题求助

解决Bevy 0.11文本无法显示的问题

问题根源

你的代码存在两个导致文本不显示的核心问题:

  1. 缺少UI渲染所需的2D相机:Bevy的UI系统依赖Camera2dBundle进行渲染,当前仅创建了3D相机,UI元素无法被捕获渲染。
  2. 空字体句柄:TextStyle中使用Default::default()会返回空字体Handle,Bevy 0.11不会自动加载内置默认字体,必须手动加载。

修改后的完整代码

use bevy::{prelude::*, ui::AlignSelf};

// 假设你已定义以下组件
#[derive(Component)]
struct LobbyText;
#[derive(Component)]
struct LobbyUI;

fn lobby_startup(mut commands: Commands, asset_server: Res<AssetServer>) {
    // 同时创建3D相机和UI所需的2D相机
    commands.spawn(Camera3dBundle::default());
    commands.spawn(Camera2dBundle::default());

    commands
        .spawn(NodeBundle {
            style: Style {
                width: Val::Percent(100.0),
                height: Val::Percent(100.0),
                position_type: PositionType::Absolute,
                justify_content: JustifyContent::Center,
                align_items: AlignItems::FlexEnd,
                ..default()
            },
            background_color: Color::rgb(0.43, 0.40, 0.38).into(),
            ..default()
        })
        .with_children(|parent| {
            parent
                .spawn(TextBundle {
                    style: Style {
                        align_self: AlignSelf::Center,
                        justify_content: JustifyContent::Center,
                        ..default()
                    },
                    text: Text::from_section(
                        "Entering lobby...",
                        TextStyle {
                            // 加载Bevy 0.11内置的默认字体
                            font: asset_server.load("fonts/FiraSans-Bold.ttf"),
                            font_size: 96.,
                            color: Color::BLACK,
                        },
                    ),
                    ..default()
                })
                .insert(LobbyText);
        })
        .insert(LobbyUI);
}

修改说明

  • 添加Camera2dBundle:UI元素仅能被2D相机渲染,必须单独创建。
  • 加载内置字体:通过AssetServer加载Bevy自带的FiraSans字体,fonts/FiraSans-Bold.ttf是0.11版本内置字体的标准路径。
  • 注入AssetServer:将Res<AssetServer>作为函数参数,让Bevy自动注入资源服务实例。

验证步骤

  1. 用上述代码替换原有lobby_startup函数
  2. 执行原复现命令:
git checkout 48b6318602a7deefeacfa2648f22b0e77ffd5611
cargo run

此时应能正常显示"Entering lobby..."文本。

内容的提问来源于stack exchange,提问作者Daniel Porteous

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 17:32:43