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!
The error is saying that you cannot add an
SKNode
that already has a parent. When you are declaring thepersonaje
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:
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:
or create a new node:
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:
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.