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)]
15pub struct Scene {
16 pub handle: i32,
17}
18
19unsafe impl Il2CppValue for Scene {
20 fn matches(ty: TypeInfo) -> bool {
21 ty.is_value_type("UnityEngine.SceneManagement", "Scene")
22 }
23}
24
25impl Scene {
26 pub fn active() -> Result<Self> {
28 SCENE_MANAGER_ACTIVE.call(())
29 }
30
31 pub fn name(&self) -> Result<String> {
32 let mut scene = *self;
34 let name = SCENE_GET_NAME.call((&mut scene as *mut Scene as *mut c_void,))?;
35 Ok(name.to_rust().unwrap_or_default())
36 }
37}
38
39type Callback = Arc<dyn Fn(Scene, LoadSceneMode) + Send + Sync>;
40
41static CALLBACKS: Mutex<Vec<Callback>> = Mutex::new(Vec::new());
42static HOOKED: Mutex<bool> = Mutex::new(false);
43
44pub fn on_scene_loaded(
47 callback: impl Fn(Scene, LoadSceneMode) + Send + Sync + 'static,
48) -> Result<()> {
49 CALLBACKS
50 .lock()
51 .unwrap_or_else(|e| e.into_inner())
52 .push(Arc::new(callback));
53 let mut hooked = HOOKED.lock().unwrap_or_else(|e| e.into_inner());
54 if !*hooked {
55 SCENE_LOADED.method()?.hook(
57 |scene: Scene, mode: LoadSceneMode, original: Original<_, ()>| {
58 original.call((scene, mode));
59 tracing::debug!(scene = scene.handle, mode = mode.0, "scene loaded");
60 let callbacks = CALLBACKS.lock().unwrap_or_else(|e| e.into_inner()).clone();
61 for callback in callbacks {
64 callback(scene, mode);
65 }
66 },
67 )?;
68 *hooked = true;
69 tracing::debug!("watching for scene loads");
70 }
71 Ok(())
72}