Error returning to previous view in swift 3 Spritkit

When I switch to my game from my menu scene, it works fine. But when I try to return, it is a disaster. I get: nil unexpectedly found while deploying an optional value. Return Code:

        let menuscene = MenuScene(size: self.size)
        menuscene.scaleMode = scaleMode
        self.view?.presentScene(menuscene)

The code from which he says the error comes from:

    PlaygamebtnNode = self.childNode(withName: "PlaygamebtnNode") as! SKSpriteNode
    NamelblNode = self.childNode(withName: "NamelblNode") as! SKLabelNode

This is strange because when the game starts, it is normal with this code. The error should come from changes in views / scenes. Thank you for your help. Code for the MenuScene class:

    import SpriteKit
    import GameplayKit

 class MenuScene: SKScene {


var PlaygamebtnNode:SKSpriteNode!
var NamelblNode:SKLabelNode!

override func didMove(to view: SKView) {

    PlaygamebtnNode = self.childNode(withName: "PlaygamebtnNode") as! SKSpriteNode
    NamelblNode = self.childNode(withName: "NamelblNode") as! SKLabelNode


    PlaygamebtnNode.texture = SKTexture(imageNamed: "Playgamebtn")
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    let touch = touches.first

    if let location = touch?.location(in: self){
        let nodesArray = self.nodes(at: location)

        if nodesArray.first?.name == "PlaygamebtnNode" {
            let transition = SKTransition.flipHorizontal(withDuration: 0.5)

            let nextScene = GameScene(size: self.size)
            self.view?.presentScene(nextScene, transition: transition)
        }
    }

}

The reason this is not an ordinary thread found when expanding on an optional value question is because it does not show this error until I return to the menu.

+4
1

:

PlaygamebtnNode = self.childNode(withName: "PlaygamebtnNode") as! SKSpriteNode 

, , self.childNode(withName:) nil

( leavegamefunc()):

let menuscene = MenuScene(size: self.size)

PlaygamebtnNode MenuScene.sks, (MenuScene.init(size:)).

:

 func leavegamefunc() {
        if let menuScene = MenuScene(fileNamed: "MenuScene"){
            menuScene.scaleMode = scaleMode
            self.view?.presentScene(menuScene)
        }
    }
+3

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


All Articles