- Home /
How to correctly use GetComponentInChildren
I have a bunch of nested objects (or will, if I get this to work) that will look like this
XXX -y --z -y -y
I'm trying to run this script (from the top, at XXX) to go through each of the children and turn off their renderer.
public Component[] ourRenderer;
if(inRadMenu == false)
{
ourRenderer = GetComponentInChildren();
foreach(Renderer renderer in ourRenderer)
{
renderer.enabled = false;
}
return;
}
However, I keep getting "Cannot implicity convert type 'UnityEngine.Renderer' to `UnityEngine.Component[]'. Is renderer not a component?
Answer by Dave-Carlile · Feb 08, 2013 at 04:02 PM
GetComponentInChildren returns a single instance. You're trying to assign the result to an array.
Looks like you probably want to use GetComponentsInChildren.
I don't know wether or not I should be upset I needed just an 's', or to be happy you were so quick!
I'll ponder on it, thanks!
Answer by Kergal · Feb 08, 2013 at 04:29 PM
I would change a couple of things. (but i use C#) . At the moment your your Array is of type component - which is weird (at least to me) . make it Transforms or GameObjects. then in your foreach loop. what do you want ? - you want to go through all the elements( that are now specified as GameObjects or Transforms ) of ourRenderer and turn them off.
so I would go with foreach (GameObject temp in ourRenderer) {
temp.renderer.enabled = false; }
// (or SetActive(false) or something like that)
however , I have not tested my approach and would -just for preference reasons use a regular for loop.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Instantiate a prefab as a child of an existing object? 1 Answer
GetComponentInChildren not Working 1 Answer
While Loop Issue 0 Answers