Question: Declaring global variables in Swift 3 Error

Question

Declaring global variables in Swift 3 Error

Answers 3
Added at 2017-01-02 18:01
Tags
Question

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!

Answers
nr: #1 dodano: 2017-01-02 19:01

I suspect you Attemped 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)
nr: #2 dodano: 2017-01-02 19:01

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)
nr: #3 dodano: 2017-01-02 19:01

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.

Source Show
◀ Wstecz