1.8 KiB
1.8 KiB
Calling JavaScript from Rust
To call a function defined in JavaScript
function on_update() {
}
We need to acquire the JsRuntime resource within a bevy system.
Then we will be able to call call_fn on it, providing the name
of the function to call, the JsScriptData that has been automatically
attached to the entity after an entity with a script attached has been spawned
and its script evaluated, the entity and optionally some arguments.
# extern crate bevy;
# extern crate bevy_scriptum;
use bevy::prelude::*;
use bevy_scriptum::prelude::*;
use bevy_scriptum::runtimes::javascript::prelude::*;
fn call_js_on_update_from_rust(
mut scripted_entities: Query<(Entity, &mut JsScriptData)>,
scripting_runtime: ResMut<JsRuntime>,
) {
for (entity, mut script_data) in &mut scripted_entities {
// calling function named `on_update` defined in JavaScript script
scripting_runtime
.call_fn("on_update", &mut script_data, entity, ())
.unwrap();
}
}
We can also pass some arguments by providing a tuple or Vec as the last
call_fn argument.
# extern crate bevy;
# extern crate bevy_scriptum;
use bevy::prelude::*;
use bevy_scriptum::prelude::*;
use bevy_scriptum::runtimes::javascript::prelude::*;
fn call_js_on_update_from_rust(
mut scripted_entities: Query<(Entity, &mut JsScriptData)>,
scripting_runtime: ResMut<JsRuntime>,
) {
for (entity, mut script_data) in &mut scripted_entities {
scripting_runtime
.call_fn("on_update", &mut script_data, entity, (123, String::from("hello")))
.unwrap();
}
}
They will be passed to the on_update JavaScript function
function on_update(a, b) {
print(a); // 123
print(b); // hello
}