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?

GetComponentsInChildren returns Component, not Collider. You can use the generic version:

var colliders = gameObject.GetComponentsInChildren.< Collider >();

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.