Skip to main content

hao_il2cpp_unity/
scene.rs

1//! Scenes, and running code when one loads.
2
3use 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/// `UnityEngine.SceneManagement.Scene`.
13#[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    /// The scene being played.
27    pub fn active() -> Result<Self> {
28        SCENE_MANAGER_ACTIVE.call(())
29    }
30
31    pub fn name(&self) -> Result<String> {
32        // Instance methods of structs take a pointer to the struct.
33        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
44/// Runs `callback` on Unity's main thread after each scene loads, which is a
45/// good time to add objects to the game. Panics are caught and printed.
46pub 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        // Unity calls this to raise `SceneManager.sceneLoaded`.
56        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                // Managed exceptions must flow back to Unity, not be caught here
62                // (Rust can't catch foreign exceptions; catching would abort).
63                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}