- Home /
Cannot cast from source type to destination type
Hi,
I got a stupid error which I can't resolve. I am trying to deactivate the rigidbodies (the ragdoll hierarchy) of multiple enemies at start:
function ActivateRagdoll( logicValue : boolean ) {
var colliders : Collider[];
colliders = gameObject.GetComponentsInChildren(Collider);
for ( var object : Collider in colliders ) {
object.attachedRigidbody.detectCollisions = logicValue;
object.attachedRigidbody.isKinematic = !logicValue;
object.enabled = logicValue;
}
}// ActivateRagdoll() End
However I get the following error message: "InvalidCastException: Cannot cast from source type to destination type." The line "colliders = gameObject.GetComponentsInChildren(Collider);" causes the errors.
Regarding this error I only stumbled upon others which had issues while instanciating.
Any clues?
Answer by Bunny83 · Sep 26, 2014 at 07:54 PM
As you can see in the examples of GetComponentsInChildren, this method returns a Component array. This can't be casted into a Collider[]. So either declare your "colliders" variable as "Component[]" like they did in the example, or use the generic version which returns an array of the actual type.
// generic version
colliders = gameObject.GetComponentsInChildren.<Collider>();
When using a Component array instead of a Collider array the for-loop will cast each element to Collider when it's accessing it.
Answer by Eric5h5 · Sep 26, 2014 at 07:53 PM
GetComponentsInChildren returns Component[], not Collider[]. You can use the generic version:
var colliders = gameObject.GetComponentsInChildren.< Collider >();
i had this same problem they should make this more clear with a note or something above the code
Your answer
Follow this Question
Related Questions
Make compiler treat an object variable as if it was of type X 2 Answers
Array of GameObjects Android/iPhone - call/typing/casting problem? 3 Answers
C# dynamic typing 3 Answers
C# Casting Compile Error 1 Answer
Change what script a var holds? 1 Answer