- Home /
Get all child objects within an object?
In blender I "fractured" a house into multiple parts. In unity, how can I properly get all the objects within the house object? My intent is to track when the player collides with each piece.
If you want to check when the player collides with your objects and want to check if it's a child of "twofloorhome" then you could try. http://docs.unity3d.com/Documentation/ScriptReference/Transform.IsChildOf.html.
Example would be: Assu$$anonymous$$g your using a CharacterController
using UnityEngine;
using System.Collections;
public class example : $$anonymous$$onoBehaviour
{
void OnControllerColliderHit(ControllerColliderHit hit) {
if (hit.transform.IsChildOf(GameObject.Find("twofloorhome").transform))
{
//Do somthing
}
}
}
if I want to destroy the children of the home, do I use Destroy(hit.gameObject);?
void OnCollisionEnter ()
{
if (transform.IsChildOf(GameObject.Find("twofloorhome").transform))
{
DestroyObject(gameObject);
}
}
This works fine when I add the script to each individual fracture. I would like to only add the script to the parent. The other suggestions will not work for either parent or children.
Answer by paulaceccon · Jan 29, 2013 at 07:43 PM
I guess you may use GetComponentsInChildren. So, you can do this:
Transform[] allChildren = GetComponentsInChildren();
foreach (Transform child in allChildren) {
// do what you want with the transform
}
This was one of the things I first tried. Unity kept showing this error UnityEngine.Component.GetComponentsInChildren()' cannot be inferred from the usage. Try specifying the type arguments explicitly
Have you tried Transform[] allChildren = GetComponentsInChildren(); ?
ins$$anonymous$$d of finding the child GameObjects you always just find their transform, the transform is just part of them that says their position. it's what everyone uses in unity to find children
I get an error when I use this, it expects a ')' but gets 'child'. I understand what it means but no idea why it's throwing that error.
I think in C# it should be:
Transform[] allChildren = GetComponentsInChildren<Transform>();
I just tried using it to deactivate all of the children of an object, and it worked perfectly in C#. The precise code was:
Transform[] allChildren = GetComponentsInChildren<Transform>();
foreach (Transform child in allChildren)
{
child.gameObject.SetActive(false);
}
Answer by Paulo-Henrique025 · Jan 29, 2013 at 09:38 PM
foreach(Transform child in gameObject.transform)
{
//Do your stuff
}
I get an error when I use this, it expects a ')' but gets 'child'. I understand what it means but no idea why it's throwing that error.