0
\$\begingroup\$

For my Unity project, I have a standard GameObject: it's an animal with 3 GameObjects nested under it (called Neem, Feem and PrintState). There are 6 Animals in my Hierarchy at the moment.

  • Snake
  • Tiger
  • Goat
  • Zebra
  • Narwhal
  • Fox

These Animal GameObjects are all tagged "ANIMAL".

In the attached screenshot, there are 3 Animal GameObjects nested under each other: the Snake is in the top level, and then Tiger nested below it, and Goat below that. The other 3 Animal GameObjects are all in the root.

enter image description here

In my data model, Animals are either in the root level or nested as only children. No Animal can ever have more than one child nested below it. (In practical terms, there would only usually be up to 5 or so Animals nested under another Animal - but that probably doesn't matter here.)

Here's the situation: If I ask Unity to look under the Snake GameObject... I'd like to get the bottommost animal GameObject nested under it. In this case of Snake, the bottommost animal GameObject would be Goat. (I wouldn't want any of the GameObjects under Goat - I want to ignore those for the purpose of this search.)

If I told Unity to look under Zebra... I'd like to get the Zebra. (Again, I'd want to ignore the 3 non-Animal GameObjects.)

Is there a way I can count the GameObjects tagged ANIMAL under a given other GameObject? Or another way to address this more directly, and get returned the bottommost GameObject tagged Animal?

Thanks!

\$\endgroup\$
2
  • \$\begingroup\$ Are you restricted to using only tags in this case, or could you create an Animal component and search for objects with a matching component, such as with GetComponentsInChildren or the singular version used recursively? \$\endgroup\$
    – DMGregory
    May 26, 2022 at 11:47
  • \$\begingroup\$ Could definitely add an Animal component if it made things easier! \$\endgroup\$
    – kanamekun
    May 26, 2022 at 11:54

1 Answer 1

1
\$\begingroup\$

Instead of a tag, I'd use a marker component, something like this:

public class Animal : MonoBehaviour {

    static Animal GetDeepestAnimal(GameObject initial) {
        if (!initial.TryGetComponent(out Animal child))
            return null;

        Animal parent;
        do {
            parent = child;
            child = parent.GetComponentInChildren<Animal>();
        } while (child != null);

        return parent;
    }
}

Place an Animal component on each animal game object.

Now you can call Animal.GetDeepestAnimal(someGameObject) to find the most deeply nested animal component in its child hierarchy, which in turn gives you access to its game object.

\$\endgroup\$
1
  • \$\begingroup\$ Amazing!! I will try it out! \$\endgroup\$
    – kanamekun
    May 26, 2022 at 12:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .