- Home /
How can I find a specific child transform of the object in the trigger?
I have a trigger with the script below. When a player is in the trigger I would like to search through their hierarchy for a specific bone (mainHandName) and assign its transform as the variable mainHandTransform. I am using the standard 3rd person Controller for the testing, but for some reason this isn't working. I can see when the player is in the trigger because the boolean is set to true, but the transform variable is not being assigned. Where am I going wrong?
public string mainHandName = "Bip001 R Hand";
public Transform mainHandTransform;
public bool inTrigger = false;
void OnTriggerStay(Collider other) {
if (other.collider.tag == "Player") {
inTrigger = true;
mainHandTransform = other.transform.Find(mainHandName);
}
}
}
Is that really your code? Your first line is missing quote marks around the string:
public string mainHandName = "Bip001 R Hand";
I'd also try FindChild rather than Find:
mainHandTransform = other.transform.FindChild(mainHandName);
Sorry for the error I copied it too quickly, in my actual code I assign it through the inspector. I have tried using FindChild ins$$anonymous$$d of Find as you suggested but it still isn't working. I have used transform.Find previously to locate transforms in the hierarchy, but I have never used transform.FindChild before. I can't find any documentation on FindChild, how different is it to regular Find?
Answer by Hamesh81 · Nov 02, 2014 at 10:57 AM
I finally worked it out! So apparently transform.Find only searches through the immediate children. Therefore in order to search through the entire bone hierarchy for a specific child/grandchild/great grandchild etc you need to first use getcomponentsinchildren and then use a foreach loop to search for the specific bone by name. I think transform.Find would be much more useful if you could actually use it for more than just the immediate child; needing to specify the entire path to get to it doesn't make it easier than a foreach loop.
Your answer
Follow this Question
Related Questions
transform.Find(string)? 2 Answers
Why GameObject.Find() work and parent.transform.Find() doesn't work? 1 Answer
FindChild not working? (Pick up Object) 2 Answers
Finding Children question 3 Answers
about transform find 2 Answers