Search code examples
iosswiftscnnode

How to check if a parent SCNNode contains a child SCNNode


In UIKit I can check if a view is a subView of another view:

if !childView.isDescendant(of: parentView) {

    parentView.addSubview(childView)

} else {

    childView.removeFromSuperview()
}

For a SCNNode what's the equivalent of .isDescendant(of: ) so I can I do the same thing with a SCNNode:

if !childNode.???(of: parentNode) {

    parentNode.addChildNode(childNode)

} else {

    childNode.removeFromParentNode()
}

Solution

  • It's childNodes.contains() and you use it like:

    if !parentNode.childNodes.contains(yourChildNode) {
    
        parentNode.addChildNode(yourChildNode)
    
    } else {
    
        yourChildNode.removeFromParentNode()
    }
    

    enter image description here

    enter image description here