Skip to content

Commit c3a7d96

Browse files
committed
refactor: Accept Handle<ScriptAsset> in ScriptComponents.
1 parent cf4dbf4 commit c3a7d96

File tree

5 files changed

+31
-45
lines changed

5 files changed

+31
-45
lines changed

crates/bevy_mod_scripting_core/src/commands.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -338,12 +338,12 @@ impl<P: IntoScriptPluginParams> Command for RunScriptCallback<P> {
338338
/// Adds a static script to the collection of static scripts
339339
pub struct AddStaticScript {
340340
/// The ID of the script to add
341-
id: ScriptId,
341+
id: Handle<ScriptAsset>,
342342
}
343343

344344
impl AddStaticScript {
345345
/// Creates a new AddStaticScript command with the given ID
346-
pub fn new(id: impl Into<ScriptId>) -> Self {
346+
pub fn new(id: impl Into<Handle<ScriptAsset>>) -> Self {
347347
Self { id: id.into() }
348348
}
349349
}
@@ -358,12 +358,12 @@ impl Command for AddStaticScript {
358358
/// Removes a static script from the collection of static scripts
359359
pub struct RemoveStaticScript {
360360
/// The ID of the script to remove
361-
id: ScriptId,
361+
id: Handle<ScriptAsset>,
362362
}
363363

364364
impl RemoveStaticScript {
365365
/// Creates a new RemoveStaticScript command with the given ID
366-
pub fn new(id: ScriptId) -> Self {
366+
pub fn new(id: Handle<ScriptAsset>) -> Self {
367367
Self { id }
368368
}
369369
}

crates/bevy_mod_scripting_core/src/handler.rs

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,7 @@ pub(crate) fn event_handler_inner<P: IntoScriptPluginParams>(
180180
for script_id in entity_scripts.iter() {
181181
match &event.recipients {
182182
crate::event::Recipients::Script(target_script_id)
183-
if target_script_id != script_id =>
183+
if *target_script_id != script_id.id() =>
184184
{
185185
continue
186186
}
@@ -197,7 +197,7 @@ pub(crate) fn event_handler_inner<P: IntoScriptPluginParams>(
197197

198198
let call_result = handler_ctxt.call_dynamic_label(
199199
&callback_label,
200-
script_id,
200+
&script_id.id(),
201201
*entity,
202202
event.args.clone(),
203203
guard.clone(),
@@ -208,7 +208,7 @@ pub(crate) fn event_handler_inner<P: IntoScriptPluginParams>(
208208
guard.clone(),
209209
ScriptCallbackResponseEvent::new(
210210
callback_label.clone(),
211-
script_id.clone(),
211+
script_id.id(),
212212
call_result.clone(),
213213
),
214214
);
@@ -234,9 +234,15 @@ pub(crate) fn event_handler_inner<P: IntoScriptPluginParams>(
234234
}
235235
_ => {}
236236
}
237-
let e = e
238-
.with_script(script_id.clone())
239-
.with_context(format!("Event handling for: Language: {}", P::LANGUAGE));
237+
let e = {
238+
239+
if let Some(path) = script_id.path() {
240+
e.with_script(path)
241+
} else {
242+
e
243+
}
244+
.with_context(format!("Event handling for: Language: {}", P::LANGUAGE))
245+
};
240246
push_err_and_continue!(errors, Err(e));
241247
}
242248
};

crates/bevy_mod_scripting_core/src/lib.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -353,21 +353,21 @@ pub trait ManageStaticScripts {
353353
/// Registers a script id as a static script.
354354
///
355355
/// Event handlers will run these scripts on top of the entity scripts.
356-
fn add_static_script(&mut self, script_id: impl Into<ScriptId>) -> &mut Self;
356+
fn add_static_script(&mut self, script_id: impl Into<Handle<ScriptAsset>>) -> &mut Self;
357357

358358
/// Removes a script id from the list of static scripts.
359359
///
360360
/// Does nothing if the script id is not in the list.
361-
fn remove_static_script(&mut self, script_id: impl Into<ScriptId>) -> &mut Self;
361+
fn remove_static_script(&mut self, script_id: impl Into<Handle<ScriptAsset>>) -> &mut Self;
362362
}
363363

364364
impl ManageStaticScripts for App {
365-
fn add_static_script(&mut self, script_id: impl Into<ScriptId>) -> &mut Self {
365+
fn add_static_script(&mut self, script_id: impl Into<Handle<ScriptAsset>>) -> &mut Self {
366366
AddStaticScript::new(script_id.into()).apply(self.world_mut());
367367
self
368368
}
369369

370-
fn remove_static_script(&mut self, script_id: impl Into<ScriptId>) -> &mut Self {
370+
fn remove_static_script(&mut self, script_id: impl Into<Handle<ScriptAsset>>) -> &mut Self {
371371
RemoveStaticScript::new(script_id.into()).apply(self.world_mut());
372372
self
373373
}

crates/bevy_mod_scripting_core/src/script.rs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,10 @@ pub type ScriptId = AssetId<ScriptAsset>;
1616
/// A component which identifies the scripts existing on an entity.
1717
///
1818
/// Event handlers search for components with this component to figure out which scripts to run and on which entities.
19-
pub struct ScriptComponent(pub Vec<ScriptId>);
19+
pub struct ScriptComponent(pub Vec<Handle<ScriptAsset>>);
2020

2121
impl Deref for ScriptComponent {
22-
type Target = Vec<ScriptId>;
22+
type Target = Vec<Handle<ScriptAsset>>;
2323

2424
fn deref(&self) -> &Self::Target {
2525
&self.0
@@ -28,7 +28,7 @@ impl Deref for ScriptComponent {
2828

2929
impl ScriptComponent {
3030
/// Creates a new [`ScriptComponent`] with the given ScriptID's
31-
pub fn new<S: Into<ScriptId>, I: IntoIterator<Item = S>>(components: I) -> Self {
31+
pub fn new<S: Into<Handle<ScriptAsset>>, I: IntoIterator<Item = S>>(components: I) -> Self {
3232
Self(components.into_iter().map(Into::into).collect())
3333
}
3434
}
@@ -111,29 +111,29 @@ impl<P: IntoScriptPluginParams> Clone for Script<P> {
111111
/// Useful for `global` or `static` scripts which operate over a larger scope than a single entity.
112112
#[derive(Default, Resource)]
113113
pub struct StaticScripts {
114-
pub(crate) scripts: HashSet<ScriptId>,
114+
pub(crate) scripts: HashSet<Handle<ScriptAsset>>,
115115
}
116116

117117
#[profiling::all_functions]
118118
impl StaticScripts {
119119
/// Inserts a static script into the collection
120-
pub fn insert<S: Into<ScriptId>>(&mut self, script: S) {
120+
pub fn insert<S: Into<Handle<ScriptAsset>>>(&mut self, script: S) {
121121
self.scripts.insert(script.into());
122122
}
123123

124124
/// Removes a static script from the collection, returning `true` if the script was in the collection, `false` otherwise
125-
pub fn remove<S: Into<ScriptId>>(&mut self, script: S) -> bool {
125+
pub fn remove<S: Into<Handle<ScriptAsset>>>(&mut self, script: S) -> bool {
126126
self.scripts.remove(&script.into())
127127
}
128128

129129
/// Checks if a static script is in the collection
130130
/// Returns `true` if the script is in the collection, `false` otherwise
131-
pub fn contains<S: Into<ScriptId>>(&self, script: S) -> bool {
131+
pub fn contains<S: Into<Handle<ScriptAsset>>>(&self, script: S) -> bool {
132132
self.scripts.contains(&script.into())
133133
}
134134

135135
/// Returns an iterator over the static scripts
136-
pub fn iter(&self) -> impl Iterator<Item = &ScriptId> {
136+
pub fn iter(&self) -> impl Iterator<Item = &Handle<ScriptAsset>> {
137137
self.scripts.iter()
138138
}
139139
}

examples/game_of_life.rs

Lines changed: 3 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,6 @@ fn console_app(app: &mut App) -> &mut App {
5454
fn run_script_cmd(
5555
mut log: ConsoleCommand<GameOfLifeCommand>,
5656
mut commands: Commands,
57-
mut loaded_scripts: ResMut<LoadedScripts>,
5857
asset_server: Res<AssetServer>,
5958
mut script_handle: Local<Option<Handle<ScriptAsset>>>,
6059
) {
@@ -71,22 +70,18 @@ fn run_script_cmd(
7170
);
7271

7372
let script_path = format!("scripts/game_of_life.{}", language);
74-
*script_handle = Some(asset_server.load(script_path));
75-
let script_id = script_handle.as_ref().unwrap().id();
7673
if !use_static_script {
7774
bevy::log::info!("Spawning an entity with ScriptComponent");
78-
commands.spawn(ScriptComponent::new(vec![script_id]));
75+
commands.spawn(ScriptComponent::new(vec![asset_server.load(script_path)]));
7976
} else {
8077
bevy::log::info!("Using static script instead of spawning an entity");
81-
commands.queue(AddStaticScript::new(script_id))
78+
commands.queue(AddStaticScript::new(asset_server.load(script_path)))
8279
}
8380
}
8481
GameOfLifeCommand::Stop => {
8582
// we can simply drop the handle, or manually delete, I'll just drop the handle
8683
bevy::log::info!("Stopping game of life by dropping the handles to all scripts");
8784

88-
// I am not mapping the handles to the script names, so I'll just clear the entire list
89-
loaded_scripts.0.clear();
9085

9186
// you could also do
9287
// commands.queue(DeleteScript::<LuaScriptingPlugin>::new(
@@ -123,8 +118,7 @@ fn game_of_life_app(app: &mut App) -> &mut App {
123118
.register_type::<LifeState>()
124119
.register_type::<Settings>()
125120
.init_resource::<Settings>()
126-
.init_resource::<LoadedScripts>()
127-
.add_systems(Startup, (init_game_of_life_state, load_script_assets))
121+
.add_systems(Startup, init_game_of_life_state)
128122
.add_systems(Update, (sync_window_size, send_on_click))
129123
.add_systems(
130124
FixedUpdate,
@@ -149,9 +143,6 @@ pub struct LifeState {
149143
pub cells: Vec<u8>,
150144
}
151145

152-
#[derive(Debug, Resource, Default)]
153-
pub struct LoadedScripts(pub Vec<Handle<ScriptAsset>>);
154-
155146
#[derive(Reflect, Resource)]
156147
#[reflect(Resource)]
157148
pub struct Settings {
@@ -174,17 +165,6 @@ impl Default for Settings {
174165
}
175166
}
176167

177-
/// Prepares any scripts by loading them and storing the handles.
178-
pub fn load_script_assets(
179-
asset_server: Res<AssetServer>,
180-
mut loaded_scripts: ResMut<LoadedScripts>,
181-
) {
182-
loaded_scripts.0.extend(vec![
183-
asset_server.load("scripts/game_of_life.lua"),
184-
asset_server.load("scripts/game_of_life.rhai"),
185-
]);
186-
}
187-
188168
pub fn register_script_functions(app: &mut App) -> &mut App {
189169
let world = app.world_mut();
190170
NamespaceBuilder::<GlobalNamespace>::new_unregistered(world)

0 commit comments

Comments
 (0)