Skip to content

Instantly share code, notes, and snippets.

@thebluefish
Created November 26, 2020 02:22
Show Gist options
  • Save thebluefish/f9fd3ac2ee7daa16b5d18214b68ed619 to your computer and use it in GitHub Desktop.
Save thebluefish/f9fd3ac2ee7daa16b5d18214b68ed619 to your computer and use it in GitHub Desktop.
Demonstrates waiting for assets to load asynchronously
use bevy::{prelude::*, asset::LoadState};
fn main() {
App::build()
.add_resource(GameState::Loading)
.add_resource(PendingAssets(Vec::new()))
.add_plugins(DefaultPlugins)
.add_startup_system(load_some_assets.system())
.add_system(loading.system())
.add_system(loaded.system())
.run();
}
#[derive(PartialEq)]
enum GameState {
Loading,
Loaded,
Game,
}
struct PendingAssets(pub Vec<HandleUntyped>);
fn load_some_assets(mut pending_assets: ResMut<PendingAssets>, asset_server: Res<AssetServer>) {
pending_assets.0.extend(asset_server.load_folder("models").unwrap());
}
fn loading(mut state: ResMut<GameState>, mut pending_assets: ResMut<PendingAssets>, asset_server: Res<AssetServer>) {
// Eventually bevy should support adding/removing systems
// Until then we must guard each system that we don't want running
// You can alternatively shuck groups of systems into a separate schedule
// See https://github.com/thebluefish/bevy_contrib_schedules for how to do that
if *state != GameState::Loading {
return;
}
// Check to see if everything's loaded, change states if it is
if asset_server.get_group_load_state(pending_assets.0.iter().map(|h| h.id)) == LoadState::Loaded {
pending_assets.0.clear();
*state = GameState::Loaded;
}
}
// I use a one-shot game state to allow systems to "hook" into this state
fn loaded(mut state: ResMut<GameState>) {
if *state != GameState::Loaded {
return;
}
println!("all assets are loaded");
// Pretend we prepare new assets, such as texture atlases
*state = GameState::Game;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment