Skip to content

Instantly share code, notes, and snippets.

@Hexodus
Last active April 14, 2017 11:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Hexodus/00c61e4fdee986c5761897e518c497bd to your computer and use it in GitHub Desktop.
Save Hexodus/00c61e4fdee986c5761897e518c497bd to your computer and use it in GitHub Desktop.
How to find out if an element is the first child of some other game object in unity?Unity GetComponentsInChildren method return all children which is not what's needed. So I'm using this method for this purpose instead.
/**
* find out if child is first level child of given GO
* @return Transform
**/
bool IsFirstLevelChildOf(Transform root, Transform child)
{
bool isFirstLevel = false;
var children = root.GetComponentsInChildren<Transform>();
foreach(var c in children) {
if (c.parent == root && c == child) {
isFirstLevel = true;
break;
}
}
return isFirstLevel;
}
//------- Usage example ----------
var yourParentElement = this.gameObject.GetComponent<SomeComponent>().content;
if ( IsFirstLevelChildOf(yourParentElement.transform, this.transform))
{
//do something amazing
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment