Molix
July 22, 2009, 10:51pm
1
I’m a bit stumped. If I call GetComponentInChildren, I get an object, but if I call GetComponent__s__InChildren I get nothing, not even the one that is there.
void Start()
{
Renderer[] rend = GetComponentsInChildren(typeof(Renderer), true) as Renderer[];
if( rend == null )
{
Debug.Log("Failed to find a renderer in " + gameObject.name );
// I don't believe you
Renderer rend2 = GetComponentInChildren(typeof(Renderer)) as Renderer;
if( rend2 != null )
Debug.Log("Liar. I found one. ");
}
}
Liar prints for every object. Wha?!
Molix
July 23, 2009, 2:11am
2
I still have no idea why that doesn’t work, and would still love to hear if anyone knows.
The only way I could get it to work was to “manually” go through the children recursively and use their renderer member variable.
In case anyone cares:
void Start()
{
List<Renderer> rc = GetRenderersInChildren( transform );
Renderer[] rend = rc.ToArray();
}
private List<Renderer> GetRenderersInChildren( Transform t )
{
List<Renderer> renderers = new List<Renderer>();
if( t.renderer != null )
renderers.Add( t.renderer );
foreach( Transform child in t )
renderers.AddRange( GetRenderersInChildren( child ) );
return renderers;
}
check:
(GetComponentsInChildren(typeof(Renderer), true)).Length
and tell us what u get.
Molix
July 24, 2009, 7:10pm
4
If I recall correctly, it was returning values, but they could not be cast to Renderer.
u answered ur self
I think it is because you r casting Component[ ] to Renderer[ ]
instead get the Component[ ] returned by GetComponentsInChildren, iterate through it and cast each element (u know is a renderer) to Renderer.
Molix
July 24, 2009, 11:44pm
6
Why are we passing (typeof(Renderer)) if it is not returning Renderers? When you call the singular version, it works as expected:
Renderer rend = GetComponentInChildren(typeof(Renderer)) as Renderer;
works, but on the same object:
Renderer rends[] = GetComponentsInChildren(typeof(Renderer)) as Renderer[];
returns null. Maybe it is not an issue with Unity, but a C# array thing?
I believe built in arrays are not reference types, and therefore the ‘as’ keyword wouldn’t work.
You might be able to make the cast using a C-Style cast, however.
Component[] rendererComponents = GetComponentsInChildren(typeof(Renderer)) ;
List<Renderer> answer = new List<Renderer>();
for(int i = 0; i < rendererComponents.Length; i++)
{
answer.Add((Renderer)rendererComponents[i]);
}
this is it more or less, didn’t compile it just typed it here
Molix
July 25, 2009, 8:42pm
9
Thanks, I believe that will work. Hopefully this will save some people some time in the future.