I am developing a game and I am trying to move from my game scene to my view controller but it gives me the error:
Error: Warning: Attempt to present <Breakout.GameViewController: 0x7f8874d19ed0> on whose view is not in the window hierarchy!.
My game is set up so I do level 1 and finish it then it takes me to the vc where I can do level 1. That works, but then when I finish level 2 and try to go back to the vc, it does not work and gives me the error.
I have looked at other posts but nothing has directly linked to this.
My Game Scene Controller:
class Level1: SKScene,SKPhysicsContactDelegate {
var ball:SKSpriteNode!
var paddle:SKSpriteNode!
var scoreLabel:SKLabelNode!
var score:Int = 0 {
didSet{
scoreLabel.text = "Score:\(score)"
}
}
override func didMove(to view: SKView) {
ball = self.childNode(withName: "Ball") as! SKSpriteNode
paddle = self.childNode(withName: "Paddle") as! SKSpriteNode
scoreLabel = self.childNode(withName: "Score") as! SKLabelNode
ball.physicsBody?.applyImpulse(CGVector(dx: 50, dy: 50))
ball.physicsBody?.mass=0.1
let border = SKPhysicsBody(edgeLoopFrom: (view.scene?.frame)!)
border.friction = 0
self.physicsBody = border
ball.physicsBody?.mass = 0.09
self.physicsWorld.contactDelegate = self
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let touchLocation = touch.location(in: self)
paddle.position.x = touchLocation.x
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let touchLocation = touch.location(in: self)
paddle.position.x = touchLocation.x
}
}
func didBegin(_ contact: SKPhysicsContact) {
let bodyAName = contact.bodyA.node?.name
let bodyBName = contact.bodyB.node?.name
if bodyAName == "Ball" && bodyBName == "Brick" || bodyAName == "Brick" && bodyBName == "Ball"{
if bodyAName == "Brick" {
contact.bodyA.node?.removeFromParent()
score += 1
} else if bodyBName == "Brick" {
contact.bodyB.node?.removeFromParent()
score += 1
}
}
}
override func update(_ currentTime: TimeInterval) {
if (score == 9) {
scoreLabel.text = "You Won!"
self.view?.isPaused = true
sleep(2)
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc = mainStoryboard.instantiateViewController(withIdentifier: "GameViewController")
self.view?.window?.rootViewController?.present(vc, animated: true, completion: nil)
level1done = true
}
if (ball.position.y < paddle.position.y) {
scoreLabel.text = "You Lost!"
self.view?.isPaused = true
sleep(2)
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc = mainStoryboard.instantiateViewController(withIdentifier: "GameViewController")
self.view?.window?.rootViewController?.present(vc, animated: true, completion: nil)
}
}
}