- Home /
How to access children's colliders.
I have some props made out of multiple child props (not merged because texturing would be harder) and I'm trying to disable their colliders through code. How do I do this?
Answer by SohailBukhari · May 11, 2017 at 02:43 PM
you can use Getchild() and the from child you can get his collider. Getchild() Returns a transform child by index. public Transform GetChild(int index); Index of the child transform to return. Must be smaller than Transform.childCount.
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
public Transform ColliderTransform;
void Start ()
{
Collider collider = ColliderTransform.GetChild(0).GetComponent<Collider>();
// do whatever you want with the collider
collider.enabled = true;
}
}
If you have multiple colliders childObject and want to disable then use
var collidersObj = gameObject.GetComponentsInChildren<Collider>();
for (var index = 0; index < collidersObj.Length; index++)
{
var colliderItem = collidersObj[index];
colliderItem.enabled = false;
}
Answer by leech54 · May 11, 2017 at 03:07 PM
public class MessWithKidsColliders : MonoBehavior {
public Collider[] colliders;
void Start(){
colliders = gameObject.GetComponentsInChildren<Collider>();
foreach(Collider c in colliders){
c.enabled = false;
}
}
Blockquote Attach this script to the game object you want to disable the children. If you are doing 2d you can change Collider to Collider2D. It will also disable the collider of the parent so you might have to check the name or something to not disable the parent.
If you know the name of the child you are looking for you can do
gameObject.transform.Find("name of the child").GetComponent<Collider>().enabled = false;
Answer by Patrick2607 · May 11, 2017 at 02:43 PM
You can do something like this:
foreach(Transform child in transform)
{
if(child.name == "SomeChildObj")
{
Collider col = child.GetComponent<Collider>();
col.enabled = false;
}
}
If you have multiple colliders, you can get all the colliders of the child and also loop through them.
Or, if you really want ALL childcolliders disabled you can do this:
Collider[] colliders = gameObject.GetComponentsInChildren<Collider>();
foreach(Collider collider in colliders)
collider.enabled = false;
Answer by SwissCore · May 11, 2017 at 03:07 PM
You can also use a composite collider (trigger) on parent which is attached to colliders on Child objects.
Im doing so for my 2D player. Seems to work :)
Your answer
![](https://koobas.hobune.stream/wayback/20220612121805im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Script detecting collisions of child object? 1 Answer
Multiple Cars not working 1 Answer
How to set parent collider equal to child collider visually? 2 Answers
Access a C# script on collison 1 Answer