swiftaugmented-realityarkitscnscenearscnview

Is it possible to change the ARKit scene's object when clicking on a button Swift


I am building and ARkit project for the first time, and what I need to do is to, first of all, I have to display a 3D Sphere in the ARSCNView. and then when I click on a button, the sphere should disappear and display a 3D cube at its place.

I was thinking about it ad that my code :

 @IBOutlet weak var sceneView: ARSCNView!
    var  objectNode: SCNNode?
    var objectScene: SCNScene?

objectScene = SCNScene(named: "sphere.dae")
objectNode = objectScene!.rootNode
sceneView.scene.rootNode.addChildNode(objectNode!)

and here is the code for the button:

@IBAction func cubeButtonClicked(_ sender: UIButton) {
          sceneView.scene.rootNode.enumerateChildNodes { (node, stop) in
            node.removeFromParentNode()
        }
        
        objectScene = SCNScene(named: "cube.dae")    
        objecteNode = objectScene!.rootNode
        sceneView.scene.rootNode.addChildNode(objecteNode!) 
    }
    

and I am facing this error

[SceneKit] Error: removing the root node of a scene from its scene is not allowed

Am I doing something wrong?


Solution

  • What I was missing in my above code is that I had to make the deletion and add two synchronize tasks. Since the Delete function is into a closure( asynchronous task). so the add function will be executed before the deletion. And by then the error will be gone.