WHy cant I create the GetComponentsInChildren(Renderer) array?

I get the following error at this line: InvalidCastException: Cannot cast from source type to destination type.
I’m really not sure why, as the code emulates the documentation perfectly. Is theresomething unique about renderer types?

var objectRenderers : Renderer[];
objectRenderers=downloadedAssetBundle.GetComponentsInChildren(Renderer);

Note: downloadedAssetBundle is an instantiated mainAsset (GameObject) from an asset bundle.

This is why I hate UnityScript. GetComponentsInChildren return type is Component[], and objectRenderers is Renderer[]. The compiler should be smart and try to do a cast automatically or at least show a compile-time error stating that the types don’t match. But no, it accepts your code and crash at runtime… < / rant>

A manual cast to Renderer[] should work:

var objectRenderers : Renderer[];
objectRenderers=downloadedAssetBundle.GetComponentsInChildren(Renderer) as Renderer[];

Here’s the final piece of working code. Note: objectRenderers is never declared. If you do declare it , it will crash.

objectRenderers=downloadedAssetBundle.GetComponentsInChildren( Renderer );
		
for (var eachPart : Renderer  in objectRenderers ) //as Renderer??
	{
		//set a transparent shader
		eachPart.sharedMaterial.shader = Shader.Find ("Transparent/Diffuse");
		eachPart.sharedMaterial.color = Color.blue;
		eachPart.sharedMaterial.color.a=0.3;
	}