access the gameObject.child.child.child .. ?

Hi there

I tried googling for an answer to what apppears to me as very obvious/easy - so im most likely doing something wrong :slight_smile:
Basically im making script - where I want to specify one gameobject - via inspector (public gameObject Aaa = objectInSceneAaa) and then i “Just” want to get to a specific object - that is a children of a child of a child of a child etc.

The hierachy in scene would be named
objectInSceneAaa/objectInSceneBbb/objectInSceneCcc etc.

So im trying:
public gameObject Aaa; and setting that to objectInSceneAaa;

So to access i would make it like this:
gameObject theChildObject = Aaa.objectInSceneBbb.objectInSceneCcc;

But this does not seem to work ?

Im trying to avoid the simpler Find function - because im planning to make it a prefab - so i assume it will have dificulties - because it will find same name in multiple places?

Thanks.
Karsten

You should just expose the target as a parameter.

However, each GameObject has a Transform.
You can use gameObject.transform.GetChild(0).GetChild(0).gameObject to get at the grandchildren.
Or you can use the Transform.Find which only searches through a specific transforms hierarchy.

Hi @ThermalFusion - thanks for very quick reply.

I think all makes sense - but the “expose the target as a parameter” - where and how do you mean i should do that?

Can i use any of the above without putting them into a function? - so they are declared in the class - before i run any functions.?

Thanks a million.

Make a public GameObject in your script. This will create a field in the inspector, then drag the child you’re looking for to that field.

thanks for you reply nilsdr - but for various reasons i would prefer hardcoding it into the script.

I tried the gameObject.transform.GetChild(0).GetChild(0).gameObject that @ThermalFusion mentioned - but this makes problems when dont want to use it inside a function.
So it seems that only way i can use the Find - or the GetChild - sinse they both use transform - i need to use them in public void start.

So any other suggestions? - :slight_smile:

Thanks

There is no way to get a reference to another object at runtime without executing code (eg GetChild or Find) in a method like Start or Update
The only other way is to declare a public variable and assign via the inspector. Reference on prefabs to children of the root prefab are maintained in the prefab process