Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: Attemped to add a SKNode which already has a parent

I'm doing a game with Swift 3 and SpriteKit and I'm trying to declare a global variable to work with it in the rest of the GameScene class but I can't. What I did:

class GameScene: SKScene {

    ...
    let personaje = SKSpriteNode(imageNamed: "Ball2.png")
    ...

After the global declaration I tried to use it in the sceneDidLoad just like that:

...
personaje.position = CGPoint.zero
addChild(personaje)
...

I don't know why but Xcode returns this error:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attemped to add a SKNode which already has a parent: name:'(null)' texture:[ 'Ball2.png' (150 x 146)] position:{0, 0} scale:{1.00, 1.00} size:{150, 146} anchor:{0.5, 0.5} rotation:0.00'

Thanks in advance for your ideas and solutions!

like image 845
HessianMad Avatar asked Jan 02 '17 17:01

HessianMad


3 Answers

I suspect you attempted to add a SKNode which already has a parent, which is not possible.

Remove the node from the prevous parent before adding it to a new one:

personaje.removeFromParent();
addChild(personaje)

or create a new node:

let newPersonaje = SKSpriteNode(imageNamed: "Ball2.png")
addChild(newPersonaje)
like image 62
shallowThought Avatar answered Nov 06 '22 05:11

shallowThought


The error is saying that you cannot add an SKNode that already has a parent. When you are declaring the personaje node as a property of the scene, you can reference it anywhere in the scene, but you need to only add it to the scene once.

If you need to add it again, you must first remove it from its parent:

personaje.removeFromParent()
addChild(personaje)
like image 25
nathangitter Avatar answered Nov 06 '22 06:11

nathangitter


As explained in the other answers you have declared and initialized a var , so there is no need to add to the current class because it's already added.

Instead of this syntax (if you will not need to change your sprite due to the getter read-only property), you can write also:

var personaje : SKSpriteNode! {
        get {
            return SKSpriteNode(imageNamed: "Ball2.png")
        }
}

// you can also use only one line for convenience:
// var personaje : SKSpriteNode! { get { return SKSpriteNode(imageNamed: "Ball2.png")} }

override func didMove(to view: SKView) {
        addChild(personaje)
}

With this code you can declare your global var but it will initialize only through the getter mode when you add it to your class.

like image 2
Alessandro Ornano Avatar answered Nov 06 '22 06:11

Alessandro Ornano