bevy/examples/asset/asset_loading.rs

82 lines
2.7 KiB
Rust
Raw Normal View History

2020-05-17 03:18:30 +00:00
use bevy::prelude::*;
fn main() {
App::build()
.add_default_plugins()
.add_startup_system(setup.system())
.run();
}
fn setup(
2020-07-10 04:18:35 +00:00
mut commands: Commands,
asset_server: Res<AssetServer>,
2020-05-17 03:18:30 +00:00
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
2020-05-17 17:29:42 +00:00
// You can load all assets in a folder like this. They will be loaded in parallel without blocking
2020-06-04 03:08:20 +00:00
asset_server
.load_asset_folder("assets/models/monkey")
.unwrap();
2020-05-17 03:18:30 +00:00
// Then any asset in the folder can be accessed like this:
let monkey_handle = asset_server
.get_handle("assets/models/monkey/Monkey.gltf")
.unwrap();
// You can load individual assets like this:
2020-06-04 03:08:20 +00:00
let cube_handle = asset_server.load("assets/models/cube/cube.gltf").unwrap();
2020-05-17 17:29:42 +00:00
// Assets are loaded in the background by default, which means they might not be available immediately after calling load().
2020-05-17 03:18:30 +00:00
// If you need immediate access you can load assets synchronously like this:
2020-06-04 03:08:20 +00:00
let sphere_handle = asset_server
.load_sync(&mut meshes, "assets/models/sphere/sphere.gltf")
.unwrap();
2020-05-17 17:29:42 +00:00
// All assets end up in their Assets<T> collection once they are done loading:
2020-05-17 03:18:30 +00:00
let sphere = meshes.get(&sphere_handle).unwrap();
println!("{:?}", sphere.primitive_topology);
2020-05-17 17:29:42 +00:00
// You can also add assets directly to their Assets<T> storage:
2020-05-17 03:18:30 +00:00
let material_handle = materials.add(StandardMaterial {
albedo: Color::rgb(0.5, 0.4, 0.3),
..Default::default()
});
2020-05-17 17:29:42 +00:00
// Add entities to the world:
2020-07-10 04:18:35 +00:00
commands
2020-05-17 03:18:30 +00:00
// monkey
2020-07-10 04:18:35 +00:00
.spawn(PbrComponents {
2020-05-17 03:18:30 +00:00
mesh: monkey_handle,
material: material_handle,
translation: Translation::new(-3.0, 0.0, 0.0),
..Default::default()
})
// cube
2020-07-10 04:18:35 +00:00
.spawn(PbrComponents {
2020-05-17 03:18:30 +00:00
mesh: cube_handle,
material: material_handle,
translation: Translation::new(0.0, 0.0, 0.0),
..Default::default()
})
// sphere
2020-07-10 04:18:35 +00:00
.spawn(PbrComponents {
2020-05-17 03:18:30 +00:00
mesh: sphere_handle,
material: material_handle,
translation: Translation::new(3.0, 0.0, 0.0),
..Default::default()
})
// light
2020-07-10 04:18:35 +00:00
.spawn(LightComponents {
translation: Translation::new(4.0, 5.0, 4.0),
2020-05-17 03:18:30 +00:00
..Default::default()
})
// camera
.spawn(Camera3dComponents {
transform: Transform::new_sync_disabled(Mat4::face_toward(
Vec3::new(0.0, 3.0, 10.0),
2020-05-17 03:18:30 +00:00
Vec3::new(0.0, 0.0, 0.0),
Vec3::new(0.0, 1.0, 0.0),
2020-05-17 03:18:30 +00:00
)),
..Default::default()
});
}