swiftxcodearkitsceneview

App crashes after i delete sceneview nodes


I added a button to my SceneView to delete placed images on a wall:

@IBAction func reset(_ sender: Any) {
sceneView.scene.rootNode.enumerateChildNodes { (node, _) in node.removeFromParentNode()
    }
}

It's working fine but after some seconds the app crashed with following warning:

com.apple.scenekit.scnview-renderer (14): Fatal error: Unexpectedly found nil while unwrapping an Optional value

In this part of my code appears the error:

    func update(anchor: ARPlaneAnchor) {

    planeGeometry.width = CGFloat(anchor.extent.x);

    planeGeometry.height = CGFloat(anchor.extent.z);

    position = SCNVector3Make(anchor.center.x, 0, anchor.center.z);



    let planeNode = self.childNodes.first!

    planeNode.physicsBody = SCNPhysicsBody(type: .static, shape: SCNPhysicsShape(geometry: self.planeGeometry, options: nil))

}

What did i do wrong?


Solution

  • Here let planeNode = self.childNodes.first! you force unwrapping the value. After removing all nodes from childNodes array, it will become empty. Use if let

    if let planeNode = self.childNodes.first{
     planeNode.physicsBody = SCNPhysicsBody(type: .static, shape: SCNPhysicsShape(geometry: self.planeGeometry, options: nil))
    }