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;
					}
				}

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.

Ah was a problem actually with my healthanddamage script, not the foreach loop. Closing this.

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");