hao_il2cpp_unity/
scene.rs1use std::{
4 ffi::c_void,
5 sync::{Arc, Mutex},
6};
7
8use hao_il2cpp_runtime::{Il2CppValue, Original, Result, TypeInfo};
9
10use crate::{bindings::*, values::LoadSceneMode};
11
12#[repr(C)]
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
15#[cfg_attr(feature = "reflect", derive(facet::Facet))]
16pub struct Scene {
17 pub handle: i32,
19}
20
21unsafe impl Il2CppValue for Scene {
22 fn matches(ty: TypeInfo) -> bool {
23 ty.is_value_type("UnityEngine.SceneManagement", "Scene")
24 }
25}
26
27impl Scene {
28 pub fn active() -> Result<Self> {
30 SCENE_MANAGER_ACTIVE.call(())
31 }
32
33 pub fn name(&self) -> Result<String> {
35 let mut scene = *self;
37 let name = SCENE_GET_NAME.call((&mut scene as *mut Scene as *mut c_void,))?;
38 Ok(name.to_rust().unwrap_or_default())
39 }
40}
41
42type Callback = Arc<dyn Fn(Scene, LoadSceneMode) + Send + Sync>;
43
44static CALLBACKS: Mutex<Vec<Callback>> = Mutex::new(Vec::new());
45static HOOKED: Mutex<bool> = Mutex::new(false);
46
47pub fn on_scene_loaded(
50 callback: impl Fn(Scene, LoadSceneMode) + Send + Sync + 'static,
51) -> Result<()> {
52 CALLBACKS
53 .lock()
54 .unwrap_or_else(|e| e.into_inner())
55 .push(Arc::new(callback));
56 let mut hooked = HOOKED.lock().unwrap_or_else(|e| e.into_inner());
57 if !*hooked {
58 SCENE_LOADED.method()?.hook(
60 |scene: Scene, mode: LoadSceneMode, original: Original<_, ()>| {
61 original.call((scene, mode));
62 tracing::debug!(scene = scene.handle, mode = mode.0, "scene loaded");
63 let callbacks = CALLBACKS.lock().unwrap_or_else(|e| e.into_inner()).clone();
64 for callback in callbacks {
67 callback(scene, mode);
68 }
69 },
70 )?;
71 *hooked = true;
72 tracing::debug!("watching for scene loads");
73 }
74 Ok(())
75}