I have several gameObjects with script attached to it. Each gameObject consists of a BODY object and LAMP object. I would like to attach those “children” to the parent script but I don’t know how.
I finished to add those manualy but its not a solution.
You can recursively travel down, or you can also use .GetComponentsInChildren() to get a collection of ALL the children of a given GameObject and iterate them.
All of the hierarchy stuff can be found through the Transform class. You can find children of a certain name with transform.Find(“Body”), for example. Note that this returns the Transform of the child object, so to assign it to your GameObject variables, you’d use something more like:
_body = transform.Find("Body").gameObject;
This is one of a number of ways, and depending on the situation may or may not be the best way, but with the limited information here it’s the one that comes to mind. This article lists a bunch of different ways to find references to other objects.
However…
I beg to differ. Assigning references manually in the inspector is, almost always, far more preferable to finding the object as done above. It’s faster (e.g. instant), it’s more obvious when a reference breaks and why it’s broken, and less likely to break the reference in the first place. What’s your objection to it?
If I may hazard a guess: If your objection is “I already made 50 of these lamps and don’t want to assign all 50 manually”… Fair enough, but you should be aware that the mistake you made there was not having made the lamp a Prefab before placing 50 of them, and this won’t be the last time that this is going to be something you have to concern yourself with.
StarManta - this is what I was looking for :). I was using |GameObject.Find but this was finding all the objects from the scene.
MY SUGGESTION to all youtube tutorial makers :)… It is a great topic for an episode. I’ve started to learn unity 5 days ago. I’ve made 3 tutorials and now I’m doing my own stuff (at least Im trying). I still have a lot of problems with understanding the logic behind this “tree structure”. I’ve made a simple PARENT - CHILDREN scene and I was counting the childrens, finding components of parents etc. but I still have problems with that.
For example why
_body = transform.Find(“Body”).gameObject;
and not transform.Find(“Body”) ??? etc.
And you are asking why I need to have that binding in script… Cause I will put a lot of those sensors in my scene and I don’t have time to set all components manualy :).
If you look at the documentation for a Transform object, you’ll find that it has an (inherited) property called .gameObject that is a live link to the GameObject this component is on.