I have a child object that needs to find the first parent object with a certain tag.
Parent Object ("Foo tag")
\
Child Object
\
Child Object
|
Child Object
|
Child Object
\
Child Object (needs to traverse up the tree until it finds the "Foo tag"
I can't just do a find for the foo tag because I have multiple objects with that tag - I need to find the one that is a parent of this child.
Here is a solution in C# (tested and working in Unity 5.1):
public static GameObject FindParentWithTag(GameObject childObject, string tag)
{
Transform t = childObject.transform;
while (t.parent != null)
{
if (t.parent.tag == tag)
{
return t.parent.gameObject;
}
t = t.parent.transform;
}
return null; // Could not find a parent with given tag.
}
if you had a commponent (like a c# class) on the gameobject that you want to find.
you could do transform.GetComponentInParent<ComponentName>().transform
this will search through all of the parents that this child is attached to
Imagine a form with three uls (as sections). Each section has several ‘li checkbox /li’ and the last one says Check/Uncheck All. Here is the code, which will change all checkboxes in same ul.