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)]
15#[cfg_attr(feature = "reflect", derive(facet::Facet))]
16pub struct Scene {
17    pub handle: i32,
18}
19
20unsafe impl Il2CppValue for Scene {
21    fn matches(ty: TypeInfo) -> bool {
22        ty.is_value_type("UnityEngine.SceneManagement", "Scene")
23    }
24}
25
26impl Scene {
27    /// The scene being played.
28    pub fn active() -> Result<Self> {
29        SCENE_MANAGER_ACTIVE.call(())
30    }
31
32    pub fn name(&self) -> Result<String> {
33        // Instance methods of structs take a pointer to the struct.
34        let mut scene = *self;
35        let name = SCENE_GET_NAME.call((&mut scene as *mut Scene as *mut c_void,))?;
36        Ok(name.to_rust().unwrap_or_default())
37    }
38}
39
40type Callback = Arc<dyn Fn(Scene, LoadSceneMode) + Send + Sync>;
41
42static CALLBACKS: Mutex<Vec<Callback>> = Mutex::new(Vec::new());
43static HOOKED: Mutex<bool> = Mutex::new(false);
44
45/// Runs `callback` on Unity's main thread after each scene loads, which is a
46/// good time to add objects to the game. Panics are caught and printed.
47pub fn on_scene_loaded(
48    callback: impl Fn(Scene, LoadSceneMode) + Send + Sync + 'static,
49) -> Result<()> {
50    CALLBACKS
51        .lock()
52        .unwrap_or_else(|e| e.into_inner())
53        .push(Arc::new(callback));
54    let mut hooked = HOOKED.lock().unwrap_or_else(|e| e.into_inner());
55    if !*hooked {
56        // Unity calls this to raise `SceneManager.sceneLoaded`.
57        SCENE_LOADED.method()?.hook(
58            |scene: Scene, mode: LoadSceneMode, original: Original<_, ()>| {
59                original.call((scene, mode));
60                tracing::debug!(scene = scene.handle, mode = mode.0, "scene loaded");
61                let callbacks = CALLBACKS.lock().unwrap_or_else(|e| e.into_inner()).clone();
62                // Managed exceptions must flow back to Unity, not be caught here
63                // (Rust can't catch foreign exceptions; catching would abort).
64                for callback in callbacks {
65                    callback(scene, mode);
66                }
67            },
68        )?;
69        *hooked = true;
70        tracing::debug!("watching for scene loads");
71    }
72    Ok(())
73}