Saturday, June 4, 2022
HomeGame Developmentunity - Discovering GameObject with Tag, excluding this object and its youngsters

unity – Discovering GameObject with Tag, excluding this object and its youngsters


You’ll be able to write a easy operate that checks whether or not an object is that this object itself or one in all its youngsters/grandchildren/and many others:

bool IsARelative(GameObject goal) {
    var me = remodel;
    var t = goal.remodel;
    whereas (t != null) {
        if (t == me) return true;
        t = t.guardian;
    }
    return false;
}

Then use that to filter the gathering of all objects with a tag all the way down to solely these that aren’t 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’ll be able to then stroll by means of that iterator to behave on every such object you discover:

void DoSomethingWithNonRelatives() {
    var nonRelatives = FindNonRelativesWithTag("Some Tag");
    whereas (nonRelatives.MoveNext()) {
        var discovered = nonRelatives.present;

        // Do one thing with `discovered`.
    }
}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments