0

i have a question regarding removing SCNNodes I have a function that makes a SCNNodes, when the Node is ready I add it with:

scene.rootNode.addChildNode(node)

then I make a new SCNNode with the function and like to remove the old one and add the new one, unfortunately SCNNode.removeFromParentNode() wont remove the old one:

func cleanUpAndAdd(){
        for node in scene.rootNode.childNodes{
            if node.name == "object" {
                node.removeFromParentNode()
                scene.rootNode.addChildNode(object)
                object.name = "object"
            } else {
                scene.rootNode.addChildNode(object)
                object.name = "object"
            }               
        }            
    }

It just adds and adds and never removes...

What am I missing?

M. P.
  • 107
  • 1
  • 10
  • Did you set your SCNViews playing property to true? sceneView.isPlaying = true Otherwise it might look like the object is not remove because the view did not redraw after you remove it. – Kai Engelhardt Jun 21 '17 at 16:38
  • I added `scnView.stop(nil)` and `scnView.play(nil)` – M. P. Jun 23 '17 at 13:19

3 Answers3

2

Note that SCNNode.childNodes is a collection (array) and so per Cocoa conventions you should not try to mutate it (SCNNode.addChildNode(_:)) while it's being enumerated. If you do so SceneKit will note generate a runtime exception, but the behaviour is undefined.

mnuages
  • 13,049
  • 2
  • 23
  • 40
  • I removed this part, thank you. I just do the cleanup and add it later. – M. P. Jun 23 '17 at 13:22
  • If by cleanup you mean `removeFromParentNode`, you shouldn't do that either because it is also mutating the collection. – mnuages Jun 23 '17 at 15:05
0

That code is correct, assuming you have set the node name. You didn't show us that part. How about adding "else print node.name"?

Hal Mueller
  • 7,019
  • 2
  • 24
  • 42
  • For clarification I am calling a function with NSNotificationCenter where I create my object and add it to the scene. When the "Notification" function gets called again I create a new object then I make the clean up and add the new one. I think I have to somehow trigger the Rendering Loop each time I make a new object... – M. P. Jun 21 '17 at 11:59
0

So. After hours of troubleshooting I realised that the SCNGeometry I was making contained also the SCNGeometry sources from the previous SCNGeometry.

So the rendering and removing was correct.

M. P.
  • 107
  • 1
  • 10