unity_native_plugin/
interface.rs

1use unity_native_plugin_sys::*;
2use std::sync::OnceLock;
3
4pub trait UnityInterface {
5    fn get_interface_guid() -> UnityInterfaceGUID;
6    fn new(interface: *const IUnityInterface) -> Self;
7}
8
9static UNITY_INTERFACES: OnceLock<UnityInterfaces> = OnceLock::new();
10
11pub struct UnityInterfaces {
12    interfaces: *mut unity_native_plugin_sys::IUnityInterfaces,
13}
14
15// maybe thread safety
16unsafe impl Send for UnityInterfaces {}
17unsafe impl Sync for UnityInterfaces {}
18
19
20impl UnityInterfaces {
21    pub fn get() -> &'static UnityInterfaces {
22        UNITY_INTERFACES.get().unwrap()
23    }
24
25    pub fn set_native_unity_interfaces(interfaces: *mut unity_native_plugin_sys::IUnityInterfaces) {
26        if !interfaces.is_null() {
27            let unity_interfaces = UnityInterfaces { interfaces };
28            let _ = UNITY_INTERFACES.set(unity_interfaces);
29        }
30    }
31
32    pub fn interface<T: UnityInterface>(&self) -> Option<T> {
33        unsafe {
34            if let Some(intf) = (&*self.interfaces).GetInterfaceSplit {
35                let guid = T::get_interface_guid();
36                let r = intf(guid.m_GUIDHigh, guid.m_GUIDLow);
37                if !r.is_null() {
38                    return Some(T::new(r));
39                }
40            }
41            None
42        }
43    }
44}