- Home /
Traverse up the hierarchy to find first parent with specific tag
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.
I could loop through each parent until I find the tag. parent = transform.parent while (parent != null) { if (parent.tag == "Foo tag")... }
Answer by TruffelsAndOranges · Jun 20, 2015 at 09:20 PM
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.
}
I think using "t.parent.transform" makes the code easier to read for most people.
Working perfect in 2020. Testes with Unity 2018.4. Thanks for sharing.
Answer by bladnman · Apr 07, 2012 at 06:06 PM
I hope this helps someone -- and please correct me where I'm wrong!
// FIND PARENT WITH TAG
function findParentWithTag(tagToFind:String) {
return findParentWithTag(tagToFind, this.gameObject);
}
function findParentWithTag(tagToFind:String, startingObject:GameObject) {
var parent = startingObject.transform.parent;
while (parent != null) {
if (parent.tag == tagToFind) {
return parent.gameObject as GameObject;
}
parent = parent.transform.parent;
}
return null;
}
Answer by chatbear69 · Jul 15, 2015 at 10:45 AM
(Tested and working in Unity 5.1)
var elevatorComponent : Transform;
function Start() {
elevatorComponent = transform.parent.parent;
}
This is only a good solution if there are definitely two levels that you want to traverse up. The OP specified that there may be varying levels up the tree before finding the tag.
This isn't a great answer to the question at all.
Answer by NiMareQ · Sep 16, 2012 at 05:45 PM
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.
$(document).ready(function(){
$('.check-all').change( function(){
$(this).closest("ul").find('input[type=checkbox]').attr('checked', $(this).attr('checked') || false );
});
});