how to use GetComponentsInChildren

I’m trying (and failing) to write an editor script in c# to apply materials to children of game objects. I usually use javascript so forgive the newbie question.

I have one that applies them to gameobjects but I can’t get it to work with just the children.

Given this example in the help file

HingeJoint[] hingeJoints = GetComponentsInChildren<HingeJoint>();
for (HingeJoint joint in hingeJoints) {
    joint.useSpring = false;
}

I thought this would work

Renderer[] children = go.GetComponentsInChildren<Renderer>();
for (Renderer rc in children) {
      rc.material = material;
}

But I always get the error

for the second line.

What is wrong here?

I’ve searched the forum and found about 100 ways to do this but all of them give me the same error.

Any particular reason why you wouldn’t just use Javascript for this then?

–Eric

I can’t find any examples that use a gui wizard written in javascript.

Also, conversely I can’t find how to get a material for a ui javascript, so I can’t even hardwire it…

I think all my scripts on the wiki are in Javascript, including the editor scripts, such as this and this, so hopefully that might help a bit.

–Eric

That’s very helpful thank you. I did manage to write a “hardwired” javascript version but a proper wizard version will be way more useful.

Good to see you have found a solution. As to the compile error in your C# script above the reason is the “for” statement. In C# to iterate through an array without using indexes you need to use “foreach”:

Renderer[] children = go.GetComponentsInChildren<Renderer>(); 
foreach (Renderer rc in children) { 
      rc.material = material; 
}
1 Like

Ahhh so it’s wrong in the help. Thank you too, it now works.