Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Going up the Hierarchy

Discussion in 'Scripting' started by RussellT, May 2, 2015.

  1. RussellT

    RussellT

    Joined:
    Feb 1, 2015
    Posts:
    18
    Hi All,

    I need to search up though my Hierarchy to see if a parent object has a certain tag. My starting point can vary, So currently I have this.

    Code (JavaScript):
    1. var oneParent =currentSelection.transform.parent;
    2. var twoParent =currentSelection.transform.parent.parent;
    Is there a better way to do this, I want a loop really that just keeps on searching up the hierarchy then tells me how many levels up it had to go to get there......

    Cheers,
    Rusty
     
  2. rrh

    rrh

    Joined:
    Jul 12, 2012
    Posts:
    331
    This is C# so you'll have to convert.

    Code (csharp):
    1.  
    2. Transform currentTarget = transform.parent;
    3. while ((currentTarget!=null)&&(!currentTarget.CompareTag("whatever"))) {
    4.   currentTarget = currentTarget.parent;
    5. }
    6. if (currentTarget == null) {
    7.  //notfound
    8. } else {
    9.  //found
    10. }
    11.  
     
  3. RussellT

    RussellT

    Joined:
    Feb 1, 2015
    Posts:
    18
    Great, Thanks for your help, I try and implement this now!