- Home /
Access components in ALL children
Hi. How do I access components in all of the children? When I used GetComponentInChildren it only changed it in one of the children, but I want all 9 to be changed.
Cheers.
Answer by Landern · Jan 08, 2013 at 05:33 PM
This wasn't tested, just an idea of iterating over comps in transform(gameObject.transform). Anyways you should be able to get the general idea i hope.
//unity script/javascript
for (var child : Transform in transform) {
for (var comp : Component in child.GetComponentsInChildren(Script)) {
comp.name = "blah";
}
}
// c#
foreach(Transform child in transform)
{
foreach(Component comp in child.GetComponentsInChildren<SomeScript>())
{
comp.tag = "blah";
}
}
So for example if I wanted to set a boolean "blah" = true in "blahScript" in all children, how would I do it?
Is it something like this? :
for (var child : Transform in transform) { for (var comp : Component in child.GetComponentsInChildren(Script)) { comp.name = "blahScript"; } }
comp.blah = true;
Actually, you don't need the outer loop, and you'll need to put the assigment into the loop, of course:
for (var comp : myScriptName in gameObject.GetComponentsInChildren(myScriptName)) {
comp.blah = true;
}
Note if the object where you attach this script to also has the Component "myScriptName" attached, it will also be processed, although it's not a child. To prevent this, you'd need the outer for-loop @Jordan suggested.
foreach (ScriptName component in gameObject.GetComponentsInChildren<ScriptName>())
{
component.blah = true;
}
Thanks :) This saved me loads of time. I thought if I couldn't get this to work I'll would have to do it through variables :D