Get self as another type (C#)

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By GreatCornDev

My script extends Spatial, but if it is attached to a RigidBody node it will access some of its methods. In GDScript I used the following:

rb = get_parent().get_node(self.name)
if rb is RigidBody: hasRb = true

In C# such a thing would not work, so I need to get the node as a RigidBody, so the code would look something like this:

rb = GetParent().GetNode<RigidBody>(Name);

However, the console output keeps throwing System.InvalidCastException. Trying different type casting still does not result in success.

Node rbNode = GetParent().GetNode(Name); //Getting the node as Node
rb = (RigidBody)rbNode; //System.InvalidCastException
rb = rbNode as RigidBody; //Returns null

Is there any way to make this work (or a better way, since GetParent().GetNode(Name) is kinda ugly and is more of a workaround than a good solution)?

try using

Rigidbody rb;
public override void _Ready(){
rb =  GetParent().GetNode<RigidBody>(Name);
}

not tested just a wild guess

Vikrant | 2021-02-23 12:15

Just as I have stated -

rb = GetParent().GetNode<RigidBody>(Name);

However, the console output keeps throwing System.InvalidCastException.

rb is declared in the class scope as private. I tried changing the accessibility levels, but to no avail.

GreatCornDev | 2021-02-23 21:24

Update
I guess C# RigidBody typecasting from assigned variables is generally broken, as there were actually multiple occurences of that, for example:

KinematicCollision col = GetSlideCollision(index);
if (col.Collider.IsClass("RigidBody")){ //Executes, so the Object is in fact a RigidBody
	RigidBody colRB = col.Collider as RigidBody; //Returns null, trying other typecast methods is still the same.
	colRB.ApplyCentralImpulse(-col.Normal * inputAxes.Length()); //NullReferenceException
}

In some of such cases I found an idiotic workaround:

col.Collider.Call("apply_central_impulse", -col.Normal * inputAxes.Length());

But getting properties like this doesn’t really work, since you can’t typecast a Variant either.

GreatCornDev | 2021-02-23 22:14