2

My app contains two scenes. Playscene.swift and gamescene.swift.

Transitioning from gamescene to playscene (where play takes place) works perfectly. However, once a gameover is reached, I have a "replay" button appear allowing the user to return back to gamescene.swift. Upon transitioning back it crashes with an error "Attempted to add a SKNode which already has a parent." Is there a correct way to transition back to a home screen or restart the game so I don't receive the error? Thank you for all your help!!

if self.nodeAtPoint(touchLocation) == self.replay {

        let scene = GameScene(size: self.size)
        let skView = self.view as SKView!
        scene.size = skView.bounds.size

        self.view?.presentScene(scene)

        let transition = SKTransition.crossFadeWithDuration(1.0)
        transition.pausesOutgoingScene = false
        skView.presentScene(scene, transition: transition)

    }

}

Gamescene.swift error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attemped to add a SKNode which already has a parent: <SKLabelNode> name:'(null)' text:'Highscore:' fontName:'Avenir-Black' position:{344, 549}'

*** First throw call stack:

mdd
  • 51
  • 7

3 Answers3

1

I feel stupid. I had added a breakpoint and wasn't paying attention. its safe to say its time for bed.

mdd
  • 51
  • 7
0

You are trying to present the same scene twice :

self.view?.presentScene(scene)

skView.presentScene(scene, transition: transition)

Maybe you wan't to do like so :

if self.nodeAtPoint(touchLocation) == self.replay {

    let skView = self.view as SKView!
    let scene = GameScene(size: skView.bounds.size)
    // Might also work with the following line instead :
    // let scene = GameScene(size: self.frame.size)

    let transition = SKTransition.crossFadeWithDuration(1.0)
    transition.pausesOutgoingScene = false

    self.view?.presentScene(scene, transition: transition)

}
lchamp
  • 6,592
  • 2
  • 19
  • 27
  • Thank you for pointing that out, I'm not sure how I missed that. I'm still getting a crash however. Only no error is showing except for a highlight on line "class PlayScene: SKScene, SKPhysicsContactDelegate". Is there a correct way to transition back to a game scene that I'm missing? – mdd Feb 25 '15 at 06:40
0

You might be declaring that SKLabelNode outside of the GameScene class, making the SKLabelNode global, you should declare it inside the class so it dies when scene A transitions to scene B.

Omar Dlhz
  • 158
  • 12