- Home /
Finding all grandchild objects with specific tag?
I can't seem to find an answer for this anywhere, so I figured I'd ask. I have a single game object with several child objects. Each of those child objects has a child object of their own with a specific tag, which I'm trying to toggle active/inactive using a C# script on the first game object. The problem seems to be that, at most, I can only find one of them. I've tried "FindGameObjectsWithTag" and "FindGameObjectWithTag" to no avail. I think it's due to the fact that I'm trying to find grandchild objects rather than child objects, but I can't seem to figure out how to work around that. I was wondering if anyone could offer any suggestions. Thank you.
Answer by Jinkata · Jul 13, 2017 at 07:45 AM
I haven't tested it yet, but something like this should work. I've edited to add a parameter to set whether or not it should be set active or not.
public void DisableChildObjectsWithTag(Transform parent, string tag, bool shouldBeActive)
{
for (int x = 0; x < parent.childCount; x++)
{
Transform child = parent.GetChild(x);
if(child.tag == tag)
{
child.gameObject.SetActive(shouldBeActive);
}
DisableChildObjectsWithTag(child, tag, shouldBeActive);
}
}
Then in your code you simply call it like this
DisableChildObjectsWithTag(this.transform, "some tag", false);
Or obviously you could pass it some other transform to loop through instead of it's own.
Basically it's just a recursive loop that loops through each child and then calls the same function on it's children. If it encounters one with the specified tag then it disables it.
$$anonymous$$y pleasure. Glad I could help!
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How can i check/wait until the gameobject will end the rotation ? 1 Answer
How can I call the Load method and/or the ShootingSettings method also only once in the Update ? 1 Answer
Integer value randomly multiples itself by 3 or 2 for seemingly no reason. 2 Answers