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

I am making a game with Swift 3 and SpriteKit, and I am trying to declare a global variable to work with it in the rest of the GameScene class, but I cannot. What I've done:

class GameScene: SKScene { ... let personaje = SKSpriteNode(imageNamed: "Ball2.png") ... 

After a global declaration, I tried to use it in sceneDidLoad just like this:

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

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

*** Application termination due to the uncaught exception "NSInvalidArgumentException", reason: "Accepted to add an SKNode that 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!

+6
source share
3 answers

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

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

 personaje.removeFromParent(); addChild(personaje) 

or create a new node:

 let newPersonaje = SKSpriteNode(imageNamed: "Ball2.png") addChild(newPersonaje) 
+5
source

The error says that you cannot add a SKNode that already has a parent. When you declare a personaje node as a property of a scene, you can refer to it anywhere in the scene, but you only need to add it to the scene once.

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

 personaje.removeFromParent() addChild(personaje) 
+2
source

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

Instead of this syntax (if you do not need to change your sprite due to a read-only property, you can also write:

 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 only be initialized in getter mode when you add it to your class.

+2
source

Source: https://habr.com/ru/post/1013710/


All Articles