- Home /
Disable Component of all child GameObjects
I want to disable the colliders for all the child gameobjects. I have the ConponentsInChildren. But I'm not sure how to go through each one to disable the component.
Answer by Hellium · Jun 29, 2015 at 09:59 AM
GetComponentsInChildren returns you an array. Just iterate through it with a for / foreach loop.
// C#
foreach( Component comp in componentList )
{
comp.enabled = false ;
}
(Replace Component by the component type you get with ConponentsInChildren)
I'm using this for disabling BoxCollider2D and I get an error when using that: foreach statement cannot operate on variables of type UnityEngine.BoxCollider2D' because it does not contain a definition for
GetEnumerator' or is not accessible
Have you tried as follow ?
// C#
BoxCollider2D colliders[] = GetComponentsInChildren<BoxCollider2D>();
foreach( Component comp in componentList )
{
comp.enabled = false ;
}
If this doesn't work, simply try :
// C#
BoxCollider2D colliders[] = GetComponentsInChildren<BoxCollider2D>();
for( int componentIndex = 0 ; componentIndex < colliders.Length ; ++componentIndex )
{
colliders[componentIndex].enabled = false ;
}
The first one worked I was using GetComponentInChildren not GetComponentsInChildren. Thanks for the help
Answer by adrien.grs · Jun 29, 2015 at 10:46 AM
Here's a tutorial for that : https://unity3d.com/learn/tutorials/modules/beginner/scripting/enabling-disabling-components
Use a loop for each child : http://docs.unity3d.com/ScriptReference/Component.GetComponentsInChildren.html
Tell me if you need more help :)
Your answer
Follow this Question
Related Questions
Disable OnTriggerStay when object has a childobject? 0 Answers
How disable a number of components of a gameobject via script? 1 Answer
Disable Button for a while 2 Answers
Suspend Mouse Look 2 Answers
Enable and Disable scripts 1 Answer