0
\$\begingroup\$

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.

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

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`.
    }
}
\$\endgroup\$

You must log in to answer this question.

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