- Home /
Accessing Script in All Children
Hey Community,
I'm beating my head against the wall with a simple problem: I want to call a method in all of my GameObject's children.
This C# script works perfectly on the first child in my GameObject:
GetComponentInChildren<target>().ColorChange();
So "target" is the script I'm trying to access, and ColorChange() is the method within that I'm hoping to call.
I've wandered around foreach loops and GetComponentsInChildren, but I'm not sure how to use either of these properly to achieve my end -- my code keeps getting compile errors.
Can someone please explain to me the proper way to do this?
Answer by kaushik-d · Jan 26, 2015 at 07:40 AM
You have to get all components on that GameObject and its children and then iterate over each of these components and call the method. Something like this:
target[] targetList = GetComponentsInChildren<target>();
foreach(target tg in targetList){
tg.ColorChange();
}
Thaaaaat works perfectly, thanks. :D I stared at that for way too long.
Your answer
Follow this Question
Related Questions
How to Access Components in Children of GameObject? 1 Answer
How to get all children gameobjects 5 Answers
Calling A Method From Another Script in C Sharp 3 Answers
GetComponent searches an objects child instead of the object 2 Answers
A Question about GetComponent() (when accessing scripts).... 2 Answers