x


Cannot cast from source type to destination type?

I'm trying to write a script that cycles between showing different objects on screen, activating the current object, and deactivating the others.

I'm using GameObject.GetComponentsInChildren() to do this, and it's giving the following error:

InvalidCastException: Cannot cast from source type to destination type. LocationCustomization.ApplyChanges()(at Assets/MyAssets/Script/LocationCustomization.js:98)

Here is the ApplyChanges function in question:

function ApplyChanges()
{
    renLoc1 = objLocations[iLocation].GetComponentsInChildren(Renderer); //Line 98
    litLoc1 = objLights[iLocation].GetComponentsInChildren(Light);  

    for(var p=0;p<renLoc1.length;p++)
        renLoc1[p].enabled = true;

    for(var p2=0;p2<litLoc1.length;p2++)
        litLoc1[p2].enabled = true;
}

The objects are declared above as such:

var objLocations : GameObject[];
var objLights : GameObject[];

private var renLoc1 : Renderer[];
private var litLoc1 : Light[];

private var iLocation : int;

The thing that's really confusing me is that I even tried copy/pasting the GetComponentsInChildren() code from the official documentation, replacing the component being called with what I'm trying to use, and it still gave the same error.

Anyone see anything that I'm not?

more ▼

asked Dec 30 '10 at 04:35 PM

user-7829 (google) gravatar image

user-7829 (google)
1 1 1 1

This won't solve your problem, but I believe that length should be capitalized: Length.

Dec 30 '10 at 04:41 PM Peter G
(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

The issue is that GetComponentsInChildren(type) returns Component[], not YourType[]

What you can do is use GetComponentsInChildren.() instead

more ▼

answered Dec 30 '10 at 04:37 PM

Mike 3 gravatar image

Mike 3
30.5k 10 65 253

This worked beautifully. Thanks a bunch.

Dec 30 '10 at 04:42 PM user-7829 (google)
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x69
x37
x12

asked: Dec 30 '10 at 04:35 PM

Seen: 2340 times

Last Updated: Dec 30 '10 at 04:35 PM