How do i get child game object with a certain tag?

I have tried this but i doesn’t work:

Destroy (transform.FindChild(GameObject.FindGameObjectWithTag("Weapon").transform.name).gameObject);

it gives me the error:
NullReferenceException: Object reference not set to an instance of an object

What would be the correct code to find a certain game object with tag.

2 Likes
foreach(Transform child in transform)
{
    if(child.tag == "Weapon")
        Destroy(child.gameObject);
}

If you can only possibly have one object with a matching tag that needs to be destroyed, add a “break” after the Destroy function call (obviously put braces around the conditional statement in that case, too).

5 Likes

Thanks, i didn’t think about for each, probably because I’ve never used it only seen it in code.

1 Like