Search code examples
swiftscenekitscnnode

Trying to replaceChildNode with node in different .scn file, why isn't it working?


I am trying to replace a node in my main .scn with another in a different .scn file. I've found the method which is

 func replaceChildNode(_ oldChild: SCNNode, 
                 with newChild: SCNNode)

but when I implement it. in my code, I get 1 warning and 2 errors:

warning= Expression implicitly coerced from 'SCNNode?' to 'Any'

error= 1.expected seperator (after with), 2.use of unresolved identifier 'with'.

even after error one fix 1 still get error 2 and the warning

I have defined my nodes the following way:

 var scene:SCNScene!
 var test3Scene:SCNScene!

in the loader it becomes:

 scene = SCNScene(named: "art.scnassets/x1.scn")
 test3Scene=SCNScene(named: "art.scnassets/test3.scn")

and the concerned function looks like this:

   @objc func buttonClicked(){
      print("clicked")
      sceneView.allowsCameraControl  = false
      if(selection=="avatar"){
        scene.rootNode.replaceChildNode(_, oldChild: scene.rootNode.childNode(withName: "test1 reference", recursively: true),
                                        with  newChild: test3Scene.rootNode.childNodes[0])
}


//scene.rootNode.childNode(withName: "test1 reference", recursively: true) being the oldChild
//test3Scene.rootNode.childNodes[0] being the new one

Can anyone help on making this work? Thanks for your time


Solution

  • The childNode(withName:recursively:) method returns an optional (SCNNode?) but replaceChildNode(_:with:) expects an SCNNode.

    You need to unwrap the optional before using it in the call.


    Additionally there are issues where both the argument labels and parameter names are used at the call site. This isn't valid. See Function Argument Labels and Parameter Names.

    scene.rootNode.replaceChildNode(_, oldChild: A
                                    with newChild: B)
    

    should be

    scene.rootNode.replaceChildNode(A,
                                    with: B)