- Home /
find ALL children of a parent
hey guys , i want to find ALL the CHILDREN of this gameobject , but this script only find me one child , help please , thanks.
var fruit : GameObject;
function Start() {
fruit = GameObject.Find("fruit");
fruit.collider.enabled = false;
fruit.renderer.enabled = false;
fruit.animation.Play("wumpa");
}
Answer by robertbu · Mar 03, 2014 at 01:07 PM
Your code doesn't find any children. It finds a game object named 'fruit' somewhere in the scene. If you only have a single level of children, you can use the code at the reference page for Transform to walk these children:
for (var child : Transform in transform) {
child.collider.enabled = false;
child.renderer.enabled = false;
child.animation.Play("wupa");
}
If you have multiple levels of children and need to find them all, you can use GetComponentsInChildren():
var children = gameObject.GetComponentsInChildren(Transform);
for (var child : Transform in children) {
child.collider.enabled = false;
child.renderer.enabled = false;
child.animation.Play("wupa");
}
Note that GetComponentsInChildren() also returns the parent, so you may need to add an explicit check.
thanks a lot for the reply @robertbu , i want to find these children with the tag "fruit" , i used FindGameObjectsWithTag , but it didn't work ! help please :s , thanks
You can do this for first level children:
for (var child : Transform in transform) {
if (child.tag == "fruit") {
child.collider.enabled = false;
child.renderer.enabled = false;
child.animation.Play("wupa");
}
}
You can alter the other example in the same way if you need all children. Note that 'FindGameObjectWithTag' finds all game object in the scene with a specific tag, not just for a particular object. But if you are only talking about one level, you could look through the list returned and only process those who's transform.parent is the game object you want as a parent.
hey @rebertbu thanks a lot it's working , but since my fruit is a child of another "child" and this "child" is a child of the Parent which has this script attached to it, so how can i get this to work ? . PS: my fruit is a child of another child , because i had a problem with the animation of the fruit , the animation doesn't play local , so that's why i put the fruit in an emptyobject.
Your answer
Follow this Question
Related Questions
(C#) How do I run something in my child's script? 2 Answers
Make a simple tree 1 Answer
Create multiple instances of an object 2 Answers
Update Parent/ Children From Script? 2 Answers