I am new to Unity. I'm trying to create a combat game.

I want to access different game objects by tag through the FindGameObjectWithTag method, but I want the script to ignore the game object and the children of the game object that contains the script and only reference non children of the game object with the exact tag.

  • \$\begingroup\$ I am not sure why exactly you are doing this and what you hope to accomplish. But I am pretty confident that if I would know, I could tell you about an easier and more efficient method to do that. \$\endgroup\$
    – Philipp
    Commented Jul 4, 2022 at 8:33

1 Answer 1


You can write a simple function that checks whether an object is this object itself or one of its children/grandchildren/etc:

bool IsARelative(GameObject target) {
    var me = transform;
    var t = target.transform;
    while (t != null) {
        if (t == me) return true;
        t = t.parent;
    return false;

Then use that to filter the collection of all objects with a tag down to only those that are not this object or its descendents:

IEnumerator<GameObject> NonRelativesWithTag(string tag) {
    var allWithTag = FindObjectsWithTag(tag);

    foreach(var candidate in allWithTag) {

        if (!IsARelative(candidate))
            yield return candidate;

You can then walk through that iterator to act on each such object you find:

void DoSomethingWithNonRelatives() {
    var nonRelatives = FindNonRelativesWithTag("Some Tag");
    while (nonRelatives.MoveNext()) {
        var found = nonRelatives.current;

        // Do something with `found`.

You must log in to answer this question.

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