![]() |
Attention | Topic was automatically imported from the old Question2Answer platform. |
![]() |
Asked By | Karatoga |
I’m trying to find out all nodes that belongs to some specific types:
void CheckRecursive(Node node)
{
var type = node.GetType();
if(typesToBeUpdated.TryGetValue(type, out var method))
{
method.Invoke(node, null);
}
foreach(var c in node.GetChildren()) CheckRecursive(c);
}
However node.GetType()
doesn’t return correct type with my script attached to a node.
For exampleclass Tweener : Node
. it always returns Node
object instead of Tweener
object.
How to get the Tweener
script object?
Cast it var type = node as Tweener
. You can use pattern matching too, e.g.
if (node is Tweener tweener)
{
tweener.Method();
}
spaceyjase | 2023-05-31 15:13
node is a C# object and GetType()
is the common C# function that returns the corresponding Type
class object, so the returnd object of GetType()
will never be Tweener
…
Karatoga | 2023-05-31 15:22
I corrected my post; you can cast the node.
spaceyjase | 2023-05-31 15:38
well I am quite sure this kind of casting will succeed when and only when Node node
variable is pointing to an instance of class Tweener
. That’s the problem: it’s actually not Tweener
, so casting will always fail, and GetType()
doesn’t return typeof(Tweener)
too…
On the other hand, typesToBeUpdated
stores Type
objects collected by some reflection magic. I can’t cast it using is
or as
keyword since I can’t directly reference their class name in code, but only their Type
objects.
Karatoga | 2023-05-31 15:54
Yeah sure, that’s a tough one as GetType()
will return the type as instanced; I think that unless you’re manually creating Tweener
then it will always return the engine’s type.
This smells as while C# has a great type system, it’s fighting with godot so perhaps here it’s be better to refactor to leverage goody’s types? Not sure what you’re up to
I think even with code like typeof(tweener).IsAssignableFrom(node.GetType())
you’ll get unstuck and that’s just nasty as it potentially introduces types and references, as you mentioned.
spaceyjase | 2023-05-31 17:00