Skip to content

When spawned during Update, SpriteMesh is one frame late compared to Sprite #23590

@GiantBlargg

Description

@GiantBlargg

Bevy version and features

main (4bbd37d)

What you did

Reproduction:

use bevy::prelude::*;

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .add_systems(Update, update)
        .run();
}

#[derive(Resource)]
struct ImageHandle(Handle<Image>);

fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
    commands.spawn(Camera2d);

    commands.insert_resource(ImageHandle(asset_server.load("branding/icon.png")));
}

fn update(
    mut commands: Commands,
    image: Res<ImageHandle>,
    key: Res<ButtonInput<KeyCode>>,
    sprites: Query<Entity, Or<(With<Sprite>, With<SpriteMesh>)>>,
) {
    if key.pressed(KeyCode::KeyF) || key.just_pressed(KeyCode::KeyS) {
        for sprite in sprites {
            commands.entity(sprite).despawn();
        }

        commands.spawn((
            SpriteMesh::from_image(image.0.clone()),
            Transform::from_xyz(300.0, 0.0, 0.0),
        ));
        commands.spawn((
            Sprite::from_image(image.0.clone()),
            Transform::from_xyz(-300.0, 0.0, 0.0),
        ));
    }
}

Run the above, tap S and wait for loading and shaders.
Hold F or tap S and observe.

What went wrong

Tapping S causes the SpriteMesh to flicker.
Holding F causes the SpriteMesh to disappear.
Neither affects the Sprite
SpriteMesh is supposed to be a drop-in replacement for Sprite so this is a bug.

Expected:
Image
Got:
Image

Additional information

I suspect the problem lies in crates/bevy_sprite_render/src/sprite_mesh/mod.rs:
add_mesh and add_material are run during Update so by the time the SpriteMesh is spawned, it is too late for this frame.
Setting add_mesh and add_material to run during PostUpdate resolves this issue, but I'm not sure if there are other considerations that I'm overlooking.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-RenderingDrawing game state to the screenC-BugAn unexpected or incorrect behaviorD-StraightforwardSimple bug fixes and API improvements, docs, test and examplesS-Needs-ReviewNeeds reviewer attention (from anyone!) to move forward

    Type

    No type

    Projects

    Status

    Needs SME Triage

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions