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    /// Unity's handle for the loaded scene; equal handles are the same scene.
18    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    /// The scene being played.
29    pub fn active() -> Result<Self> {
30        SCENE_MANAGER_ACTIVE.call(())
31    }
32
33    /// The scene's name, as listed in the game's build settings.
34    pub fn name(&self) -> Result<String> {
35        // Instance methods of structs take a pointer to the struct.
36        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
47/// Runs `callback` on Unity's main thread after each scene loads, which is a
48/// good time to add objects to the game. Panics are caught and printed.
49pub 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        // Unity calls this to raise `SceneManager.sceneLoaded`.
59        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                // Managed exceptions must flow back to Unity, not be caught here
65                // (Rust can't catch foreign exceptions; catching would abort).
66                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}