+1 vote

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)?

Godot version 3.2.3 Stable Mono x64
in Engine by (21 points)

try using

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

not tested just a wild guess

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.

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.

Please log in or register to answer this question.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.