InvalidCastException in a code from script reference?

I have an empty game object with children that have hingejoints. The parent (empty) game object has the following script attached to it:

function Update () {

var hingeJoints : HingeJoint[];

hingeJoints = GetComponentsInChildren (HingeJoint);

for (var joint : HingeJoint in hingeJoints) {

  joint.useSpring = true;



I get the error message:

InvalidCastException: Cannot cast from source type to destination type.

This is the exact same code as is used in the Unity Script Reference here. I'm not an experienced javascript user, so forgive me if I overlooked something very simple. But I think it's strange nonetheless that the unity example doesn't work... Can someone help me out?

I can't pretend to everything that JavaScript can and cannot do behind the scenes, so I suggest you learn how to use type safety, which will speed up your code and generally yield more helpful errors.

function Update () {
    var hingeJoints = GetComponentsInChildren.<HingeJoint>();
    for (var joint in hingeJoints) joint.useSpring = true;

See? It's not so bad; it's actually even less typing! ;-D You could even do

function Update () {
    for (var joint in GetComponentsInChildren.<HingeJoint>()) joint.useSpring = true;

if you didn't need that array again.

You should report a bug about the example not working, though, certainly.


Nevermind, JavaScript is broken. C# recommended until it's not. Well, C# recommended thereafter, too. :-P

C# version:

foreach (HingeJoint joint in GetComponentsInChildren<HingeJoint>()) joint.useSpring = true;

Another Edit:

Here's some JS you can use for now, until they get the generic form of GetComponentsInChildren fixed:

var hingeJoints = System.Array.ConvertAll(
    function (component) component as HingeJoint

Just an update here, afaik Javascript is not Broken as the other answer describes. What is happening here is that GetComponentsInChildren in Javascript returns an array of Components rather than specifically an array of HingeJoint(s).

You can get around this by doing the following -

var hingeJointComponents : Component[] = GetComponentsInChildren(HingeJoint);
var hingeJoint : HingeJoint;

for (var i=0; i< hingeJointComponents.Length; i++) {
	hingeJoint = hingeJointComponents *as HingeJoint;*
  •   hingeJoint.useSpring = true;*
  • }*
    Here we are creating an array of components called hingeJointComponents, and populating it with GetComponentsInChildren. However, it is still of type Component, so we need to convert each entry when we iterate through the array in a for loop, using a separate single HingeJoint typed variable to assign each one to, typing it to HingeJoint when we grab each one with the index value, taken from the i variable in the for loop. We then set useSpring on that entry.