- Home /
GetComponentInChildren< Renderer > failing to find the renderer
link textI needed to shift the pivot of a prfab, so I created an empty game object at the position I want my pivot. Then I made the prefab a child of it. Then I turned this new construct into a prefab that I use at runtime to instantiate objects. I need to get the renderer of the actual game object and I'm using this call:
Renderer renderer = wall.GetComponentInChildren< Renderer >();
The child object indeed has an active renderer attached, but the above call always returns null. I also tried changing Renderer to MeshRenderer with no luck. Prior to parenting the prefab, I was able to get the renderer by simply saying:
wall.renderer
The parent object has only one component: the transform, and only one child: a wall model. The wall model has four components: Transform, MeshFilter, MeshRenderer, and Collider.
From what I see in the docs, this call should succeed. Any idea what I'm doing wrong? Is there a better, or different way to do this?
Thanks.
If the renderer is attached to the wall, why do you call GetComponentInChildren ? Should still work though ...
Is the gameObject active ?
Hi Berenger. Thanks for the reply. I have a ref to the parent object and the renderer is attached to it's child, so it seems natural to call GetComponentInChildren rather than first get the child and then get the renderer. At first I tried calling GetComponent() directly on the parent, but that also brought back null. How would you get the renderer?
Yes, the gameObject is active. I can see the wall being rendered, they are just all piled up on each other since I have no size data to position them. Consequently, that's why I grab the renderer. I need the bound from it.
Could you create a project with just that issue and upload it ? I don't see any reasons for it not to work, so I need to see what's going on.
And if you use GetComponentInChildren<$$anonymous$$eshRenderer>() does it work?
@Berenger: I attached a simple project demonstrating my issue.
@whydoidoit: I'm scripting in C# and only see the one generic function available from GameObject, so I think I'm already using the one you asked about. Please correct me if I'm wrong, or misunderstood you reply.
Thank you both for the help.
Answer by Berenger · Jun 11, 2012 at 04:18 PM
Ok, thanks for the package.
You're trying to access the renderer on your prefab, not the instance of the prefab. That's why you get the error. So, either replace
Renderer renderer = wall.GetComponentInChildren< Renderer >();
by
GameObject inst = Instantiate( wall, Vector3.zero, Quaternion.identity ) as GameObject;
Renderer renderer = inst.GetComponentInChildren< Renderer >();
Or drag the prefab into yur scene and give that reference.