Search code examples
iosswiftsprite-kitsknode

SpriteKit: find all descendants of SKNode of certain class?


This question shows how to find all children of a SKNode that belong to a certain class, but what if we want all descendants (e.g., grandchildren) that belong to a certain class?

Is there a native way to do this in SpriteKit, or is the only option to create a recursive form of the solution from the aforementioned question?

The SKNode documentation highlights a search function that lets you find descendants with a certain name, but is there a way to filter descendants by class and not be name? We don't want to assign names to nodes if avoidable.

We're using Swift 3.


Solution

  • What we did was pass a block to the SKNode function that finds nodes by name, and used * as the search term to avoid assigning a name to desired nodes.

        var descendants = [CustomClass]()
        nodeToSearch.enumerateChildNodes(withName: ".//*") { node, stop in
            if node is CustomClass {
                descendants.append(node as! CustomClass)
            }
        }