adrien-bon / bevy_ecs_tiled

Helpers for working with 2D tilemaps created with the Tiled map editor
MIT License
34 stars 8 forks source link

Map entity does not have all components if not spawned immediately after loading asset #23

Closed giusdp closed 3 months ago

giusdp commented 3 months ago

I'm having this problem with using bevy_asset_loader where I'm loading all assets (including tiled maps) at the start and then at some point in the future (when getting to the play screen) I spawn a map. The entity is created but it only has the TiledMapBundle components, and not the others the library fills in usually.

Looking at the code I think the problem is that the completion of a map entity is tied to the Added Asset event, which happens only when the asset is loaded. I guess this means if the entity (with TiledMapBundle) isn't spawned in the same frames the asset is loaded, that event will be fired and nothing happens (cause no map entity yet) and then spawning maps with that asset will be useless.

I saw the same result by using asset_server.load("finite.tmx") in one system, then waiting 10 seconds with a timer in another system and finally spawn the map. The code to finalize the map with all the other components was not run cause there wasn't an Added Asset event.

At least this is what I understood from the code. A solution to this that I'm using is to drop the Added event and instead use the spawn command pattern (as shown in the Bevy quickstart template).

Basically there is a custom command

pub struct SpawnTiledMap {
    pub bundle: TiledMapBundle,
}

impl Command for SpawnTiledMap {
    fn apply(self, world: &mut World) {
       // spawn the complete map here
    }
}

Then the user can spawn maps using commands in a system:

let spawn_tiled_map = SpawnTiledMap {
    bundle: ...
};
commands.add(spawn_tiled_map); <-- this will spawn the command

This decouples the spawning of a map from the Added asset event so I can spawn maps later. The other assets events are fine like that.

What do you think of this change @adrien-bon ?

adrien-bon commented 3 months ago

Hi! Thanks for the issue. I did not encounter this in my project since I use the map as soon as I load it. Please fill in a PR if you can, I'll have a look over the week-end. Thanks!

adrien-bon commented 3 months ago

Merged a fix for this issue in #27, waiting for a status on #24 before closing

adrien-bon commented 3 months ago

Fixed by #27