steff feyens steff feyens - 5 months ago 39
iOS Question

Switching scenes error

I'm trying to create a little game but when the app switches to the game scene (when pressing the restart button), than this game scene won't load correctly. It'll give an error: thread 1 exc_bad_instruction (code=exc_i386_invop subcode=0x0). The whole game works fine in the beginning (if I didn't died yet) but when I die I'll go to another scene with a restart button and once this restart button is pressed I'll go again to the game. I won't even get the right background etc.


Game Scene (in this part the error will happen)

func enemySpawn() {

let enemy = SKSpriteNode(imageNamed: "Enemy")

let minValue = self.size.width / 8
let maxValue = self.size.width - 150

let spawnPoint = UInt32(maxValue - minValue) // HERE IS THE ERROR

enemy.position = CGPoint(x: CGFloat(arc4random_uniform(spawnPoint)), y: self.size.height)

enemy.physicsBody = SKPhysicsBody(rectangleOf: enemy.size)
enemy.physicsBody?.affectedByGravity = false
enemy.physicsBody?.categoryBitMask = physicsCatagory.enemy
enemy.physicsBody?.contactTestBitMask = physicsCatagory.bullet
enemy.physicsBody?.isDynamic = true

let action = SKAction.moveTo(y: -70, duration: TimeInterval(enemyMoveSpeed))
let actionDone = SKAction.removeFromParent()[action, actionDone]))


This is the restart scene:

var restartButton : UIButton!

override func didMove(to view: SKView) {

scene?.backgroundColor = UIColor.white

restartButton = UIButton(frame: CGRect(x: 0, y: 0, width: view.frame.size.width / 3, height: 30)) = CGPoint(x: view.frame.size.width / 2, y: view.frame.size.height / 7)

restartButton.setTitle("Play Again", for: UIControlState.normal)
restartButton.setTitleColor(, for: UIControlState.normal)
restartButton.addTarget(self, action: #selector(StartViewController.restart), for: UIControlEvents.touchUpInside)


func restart() {
self.view?.presentScene(GameScene(), transition: SKTransition.crossFade(withDuration: 0.3))

I hope someone will be able to help me!


My personal impression is that you get the error from the previous (disposed scene.), but I might be wrong...

let nextScene = GameScene(size: self.scene.size)
        nextScene.scaleMode = SKSceneScaleMode.AspectFill

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

I would pass size to the GameScene, instead of default constructor.