Error: Attemped to add a SKNode which already has

2019-04-26 19:32发布

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!

3条回答
我命由我不由天
2楼-- · 2019-04-26 20:17

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)
查看更多
Lonely孤独者°
3楼-- · 2019-04-26 20:28

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)
查看更多
Fickle 薄情
4楼-- · 2019-04-26 20:29

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.

查看更多
登录 后发表回答