Attemped to add a SKNode which already has a parent

In my game I’ve created some sks files with complicated animations, I’ve created custom classes for them. Then I insert them in GameScene.sks.
I need to create some duplicated sprites (falling down from the top) and I wrote function with addChild method in GameScene file. When I try to add 100 similar nodes I’ve got error “Attemped to add a SKNode which already has a parent”. I checked internet forums and I found that I can use removeFromParent before addChild. It works, but that’s not the same that I want.
How to copy/place in game scene some similar nodes (based on node with complicated animation in sks file) - simultaneously?

How are you creating your nodes? Seems like you need to create as many nodes as you want to add to avoid the “already has a parent” method. If you are reusing the sprites can’t you just reposition them when they exit your screen and have them re-enter from the desired direction?

Initially I create nodes in sks file. In each sks file there are body and two parent hands, they are have some animation. At all there are 3 different sks files with this nodes and animation.
Then in gamescene.swf I add:
class GameScene: SKScene {
var bedNode: BedNode! //class with 1st node

override func didMove(to view: SKView) {
bedNode = childNode(withName: “//bed_body”) as! BedNode //initialization node with all parts

func BedSand() {
bedNode.position = … bedNode.physicsBody = … = “…”

Then I call BedSand for some times.
I can use simple sprites and addchild them as much as I want, with sprites this code is working. But I want to have animated sprites, that’s why I use sks files and try to add it on main gamescene.

But maybe, the better way just used sprites (not in sks files) and make dynamic animations (move, rotate, scale, etc.) …

That’s the way I would do it. You could have a factory class that can give you the required kind of sprite depending on the arguments you pass to it.

But back to the original - SKNode supports NSCopying. Did you try to copy these nodes? I just tried:

    let node : SKNode = SKNode()
    let otherNode = node.copyWithZone(nil)
    node.addChild(otherNode as! SKNode)
    let anotherNode = node.copyWithZone(nil) as! SKNode

And saw that anotherNode.parent is nil.

1 Like

Thank you Adam,
CopyWithZone is working and inherit animation from parent node to child :slight_smile: But there are a lot of duplicate sprites, when I run function only 3 times - it gives me a lot of nodes, because every copy create 2 new cope and then create new copy and copy of parent… When I run function 10 times I received 250+ nodes :confused: Also, I see that fps increase too small, I’ll try to use simple sprite (with the same animation) and compare this two options.

Anyway, thanks again.