尝试用不同.scn文件中的node替换ChildNode,为什么它不起作用?

问题描述

我正在尝试将主.scn中的一个节点替换为另一个.scn文件中的另一个节点。 我找到了一种方法

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

但是当我实现它时。在我的代码中,我收到1条警告和2条错误

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

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

即使在错误1修复1之后仍然得到错误2和警告

我已经通过以下方式定义了节点:

 var scene:SCNScene!
 var test3Scene:SCNScene!

在加载程序中变为:

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

和相关的函数如下所示:

   @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

有人可以帮助完成这项工作吗?谢谢您的时间

解决方法

childNode(withName:recursively:)方法返回一个可选的(SCNNode?),但是replaceChildNode(_:with:)期望一个SCNNode

在通话中使用可选选项之前,需要先将其拆开。


此外,在调用站点上同时使用参数标签和参数名称时也会出现问题。这是无效的。参见Function Argument Labels and Parameter Names

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

应该是

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