Hello,
I have a gameobject that has 5 childrens. Each child has 5 more childrens. And so on for, let’s say 4 levels. Is there any easy way to get all the GameObjects?
Thank you!
Hello,
I have a gameobject that has 5 childrens. Each child has 5 more childrens. And so on for, let’s say 4 levels. Is there any easy way to get all the GameObjects?
Thank you!
Did you try the following?
GameObject.Find ("ExactNameOfTheObject");
But what if I don’t know how many childrens and their names? Let’s say the same script it’s gonna be on different gameobjects. One will have 30 childrens while another one only 10.
The best would be that you tell what you want to do exactly. ![]()
Are you trying to find a specific child or…grandchild as you put it, or are you finding all these object and caching them in a list or array somewhere? How is the object going to be used after it’s found?
var allOfThem = GetComponentsInChildren<Transform>();
Note that GetComponentsInChildren also returns the root object, so you’ll have to filter it out if that’s not what you want. You also get the Transforms, rather than the GameObjects. GetComponentsInChildren only returns components*.
You can use Linq to filter the result to get exactly what you want;
var allTheTransforms = GetComponentsInChildren<Transform>();
var whatICareAbout = allTheTransforms.Where(t => t != transform).Select(t => t.gameObject).ToList();
GetComponentsInChildren is great for a shotgun approach.
If you want a little more control you can iterate over Transform in a foreach loop. Do it recursively and you can access every Transform, and hence every GameObject.
Thank you very much for your replay. Yes I wanted a shotgun approach. But what I don’t get is why I get also the father.
Transform[] conversations = transform.GetComponentsInChildren<Transform>();
foreach(Transform c in conversations){
c.gameObject.SetActive(false);
}
Thank you… The GetComponentsInChildren did the trick for what I needed.
But what I don’t get is why I also get the father:
Transform[] conversations = transform.GetComponentsInChildren<Transform>();
foreach(Transform c in conversations){
c.gameObject.SetActive(false);
}
Best regards.
That’s just how GetComponentsInChildren works. Its not the clearest naming convention ever. But it does work.
Oh… so with this solution there is no way I can exclude the father.
Not unless you copy-paste the code I put in my post.
Oh sorry. I’ve missed that. It’s working . Thank you very much
For your code, there is a simpler way.
Transform[] conversations = transform.GetComponentsInChildren<Transform>();
foreach(Transform c in conversations){
if (c != transform) c.gameObject.SetActive(false);
}
That’s just perfect. Thanks