unity_mirror_rs/unity_engine/
mono_behaviour.rs1use crate::commons::Object;
2use crate::commons::RevelWeak;
3use std::any::{Any, TypeId};
4
5pub trait MonoBehaviour: Object + MonoBehaviourAny {
6 fn awake(&mut self) {}
7 fn on_enable(&mut self) {}
8 fn on_validate(&mut self) {}
9 fn start(&mut self) {}
10 fn fixed_update(&mut self) {}
11 fn update(&mut self) {}
12 fn late_update(&mut self) {}
13 fn on_disable(&mut self) {}
14 fn on_destroy(&mut self) {}
15}
16
17pub trait MonoBehaviourAny {
18 fn as_any(&self) -> &dyn Any;
19 fn as_any_mut(&mut self) -> &mut dyn Any;
20 fn type_name(&self) -> String;
21
22 fn self_type_id(&self) -> TypeId;
23 }
25
26impl<T: MonoBehaviour + 'static> MonoBehaviourAny for T {
27 fn as_any(&self) -> &dyn Any
28 where
29 Self: Sized,
30 {
31 self
32 }
33
34 fn as_any_mut(&mut self) -> &mut dyn Any
35 where
36 Self: Sized,
37 {
38 self
39 }
40
41 fn type_name(&self) -> String {
42 format!("{}", std::any::type_name::<T>())
43 }
44
45 fn self_type_id(&self) -> TypeId {
46 TypeId::of::<T>()
47 }
48}
49
50impl<T: ?Sized + MonoBehaviour + 'static> RevelWeak<Box<T>> {
51 pub fn downcast<TO: Any>(&self) -> Option<&RevelWeak<Box<TO>>> {
52 if self.get()?.as_any().downcast_ref::<TO>().is_none() {
53 return None;
54 }
55 Some(unsafe { &*(self as *const dyn Any as *const RevelWeak<Box<TO>>) })
56 }
57
58 pub fn parallel<TO: Any>(&self) -> Option<&RevelWeak<TO>> {
59 Some(unsafe { &*(self as *const dyn Any as *const RevelWeak<TO>) })
60 }
61}