- Home /
Accessing children of a gameObject by name
Hi,
I am trying to access a child object on my gameObject using its name, then access a a script on it. I cant figure out why its not working. Would someone mind taking a look and seeing if I did something wrong here? There is no errors, it just never accesses the other script ( I have a debug.log statement in the other script that never runs when the bool is set to true).
_players is an array of GameObjects btw. Thanks!
foreach (Transform child in _players[cnt].transform)
{
if(child.name == "Trigger")
{
_healthAndDamageScript = child.GetComponent<HealthAndDamage>();
_healthAndDamageScript.takingWaterDamage = true;
}
}
Answer by madmike6537 · Feb 13, 2013 at 02:17 AM
Ah was a problem actually with my healthanddamage script, not the foreach loop. Closing this.
Answer by Proportion1 · Feb 13, 2013 at 02:19 AM
it could be that the foreach condition should be a gameobject instead of a transform.
foreach (Gameobject child in _players[cnt]) // assuming that the array is full of gameobjects.
also double check that the object actually has the correct name. did u possibly mean to use child.tag instead of child.name? also as a handy hint just a debug.log outside the "if" condition so that you actually know that your code is getting to that part of your script.
Thanks - free 1 up for you even though I realized it was a script issue earlier. I appreciate the reply.
Answer by aldonaletto · Feb 13, 2013 at 02:20 AM
You can find a child by name with Transform.Find:
Transform child = _players[cnt].transform.Find("Trigger");
if (child){
_healthAndDamageScript = child.GetComponent<HealthAndDamage>();
_healthAndDamageScript.takingWaterDamage = true;
}
But if "Trigger" is deeper in the hierarchy, you must pass the complete path instead of just the child name. For instance: if "Trigger" is a child of "Body", and "Body" is a child of the _players[n] object, you should pass "Body/Trigger" to Find:
Transform child = _players[cnt].transform.Find("Body/Trigger");
Your answer
![](https://koobas.hobune.stream/wayback/20220613092613im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to use GetComponent in a foreach loop? 3 Answers
Get Component or Check if Null SoftLocks Game (C#) 1 Answer
C# Getting a certain AnimationState using strings from all objects with specific tag 2 Answers
Definition problem 1 Answer
Looping through materials on a mesh with foreach() in Start() is causing lasting FPS drop? 1 Answer