GetComponent and Renderers

Let’s say I assign a gameobject in the inspector to a variable (“obj”) in script. Let’s say the gameobject does not have a renderer, but one of its children does. When I use this:

var objRenderer : Renderer = obj.GetComponentInChildren(Renderer);

I get an error saying that I can’t cast from source to destination. Why is that?

Ok. Seriously. GetComponentInChildren is very buggy when it comes to Renderers. Apparently, I cannot assign a renderer to a variable when the script loads (ie - in Awake()) using GetComponentInChildren(Renderer), but I can assign the renderer to a variable inside of a function using the same function. That makes absolutely no sense to me, so, therefore, GetComponentInChildren is broken when it comes to Renderers.

I don’t usually write Unity javascript, but this was working for me…

var obj : GameObject;

function Awake()
{
	var objRenderer : Renderer = obj.GetComponentInChildren(Renderer); 	
	Debug.Log(objRenderer.name);
}

If the Debug.Log throws a null exception it was unable to find a renderer on the object… but if you give it a valid object it should get the first renderer in the object. One thing to make sure of is that you are using a GameObject from the hierarchy (scene) and not a prefab from the project (assets) view.