Getting children objects?

Say we have a situation like this on the hierarchy.

Cube
-----BabyCube

How can I access BabyCube (member of the Cube) and access it’s properties or components. Thanks :slight_smile:

The same way you would anything else. Find, direct reference or if instantiating, caching the reference.

Find? Really? For a child block? Can’t I do something like gameObject.BabyCube;

Example please?

It’s still just another gameobject, the parent doesn’t have direct knowledge of the children.

You could also get all the children and loop through them but find will be faster

http://lmgtfy.com/?q=unity+access+child

There are several ways, depending on your needs.

  • Transform.Find is great to find a child with a specific name.
  • GetComponentInChildren is great to find a specific component. There is also GetComponentsInChildren
  • Transform.GetChild is great if you know the index
  • And if you just want all the children then Transform itself is iterable, you can simply use foreach (Transform child in transform)
2 Likes
transform.GetChild(index).GetComponent<>();

Transform.Find is probably the cleanest option. I typically use gameobject.find(name+“/childname”)… But mostly out of habit. Also that method assumes your gameobject has a unique name.

1 Like

Most of the time I iterate through transform. I find relying on names tends to be fragile. But the standards in my studio are pretty lax.

1 Like

Honestly, I mostly use inspector references, but most of my development is prototyping, so it lets me rewire quickly. It’s gets ugly over time though. :wink:

For release code, we primarily use names, but have a very strict naming convention. It is fragile, but our pipeline tools in maya and the asset pipeline enforce and either throw a warning or corrects in some cases. Or as we call it "artist proofing ". :wink:

For our new game the pipeline has been rewritten, and sort of does it similar to unity where everything has an auto generated key that is stored in unity meta, and maya meta, both aren’t visible to the user. A data base ties the keys to cms and the names. The goal being that designers will actually browse by assets on web page, and name can change on either end and all the relationships remain. It’s early days but so far working smoothly.

1 Like

Thanks guys!

1 Like