- Home /
How do I get components in grandchildren?
How do I access a component, such as a script, that's in the grandchild of the game object with the script I'm working with? Here is my specific situation: I have a "Player" game object with a child game object called "Weapons", and that has children, one of which is a "Sword" game object. The player has a "PlayerScript" which I'm trying to access "SwordScript" in the Sword game object. Here is a visual representation:
The way I am trying to do this is as follows (this code comes from the "PlayerScript" script attached to the Player game object:
SwordScript _swordscript = this.GetComponentInChildren<Transform>().gameObject.GetComponentInChildren<SwordScript>();
The first GetComponentInChildren() should be getting the Transform that is in the Weapons gameobject, and that should be getting the SwordScript in its child.
I realize this may not be a very intuitive way to access the grand child (if I'm even remotely close to this code working), so any suggestions on how to better access the script in the grand child I would really appreciate.
Answer by tanoshimi · Feb 23, 2015 at 10:01 PM
GetComponentInChildren uses depth-first search to search all children (and their children, and their children's children) of an object to find the first occurrence of a specified component. So, if Sword is the only object to have the SwordScript script on it, you can access it from "Player" simply using:
SwordScript _swordscript = this.GetComponentInChildren<SwordScript>();
http://docs.unity3d.com/ScriptReference/Component.GetComponentInChildren.html
Answer by sebastian-pi · Aug 27, 2017 at 04:59 PM
I see that a lot of people still come to this question. Better and more relevant answer would be to use
SwordScript _swordscript = this.transform.Find("Weapons/Sword").gameObject.GetComponent<SwordScript>();
Here is documentation and a wider example: https://docs.unity3d.com/ScriptReference/Transform.Find.html
Using find is pointless in this case. Unless you had multiple weapons, all using the same script, a child of Weapon, and you wanted one specific weapon, it is better to just use GetComponentInChildren. Its simply more concise (I've also heard horror stories from Unity Technologies devs about .Find() so I'd wager GetComponentInChildren is more optimised too)
If as I said, you had multiple gameobjects with the same script in the same parent, sure. You'd probably have to use find. But even then it may just be better to instantiate a new instance of whatever you're after ins$$anonymous$$d of storing multiple copies of something ;)