Created
November 26, 2020 02:22
-
-
Save thebluefish/f9fd3ac2ee7daa16b5d18214b68ed619 to your computer and use it in GitHub Desktop.
Demonstrates waiting for assets to load asynchronously
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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