use crate::builtin::NodePath;
use crate::classes::{Node, PackedScene};
use crate::meta::{AsArg, arg_into_ref};
use crate::obj::{Gd, Inherits};
impl Node {
pub fn get_node_as<T>(&self, path: impl AsArg<NodePath>) -> Gd<T>
where
T: Inherits<Node>,
{
arg_into_ref!(path);
self.try_get_node_as(path).unwrap_or_else(|| {
panic!(
"There is no node of type {ty} at path `{path}`",
ty = T::class_id()
)
})
}
pub fn try_get_node_as<T>(&self, path: impl AsArg<NodePath>) -> Option<Gd<T>>
where
T: Inherits<Node>,
{
arg_into_ref!(path);
self.get_node_or_null(path)
.and_then(|node| node.try_cast::<T>().ok())
}
}
impl PackedScene {
pub fn instantiate_as<T>(&self) -> Gd<T>
where
T: Inherits<Node>,
{
self.try_instantiate_as::<T>()
.unwrap_or_else(|| panic!("Failed to instantiate {to}", to = T::class_id()))
}
pub fn try_instantiate_as<T>(&self) -> Option<Gd<T>>
where
T: Inherits<Node>,
{
self.instantiate().and_then(|gd| gd.try_cast::<T>().ok())
}
}