I am currently making a game in which you are a space ship in the middle and there are enemy ships moving towards you and you have to shoot at them to win.
While I was testing the game I saw that I received an error when (it appears to be) two or more enemy ships hit the player ship at the same time. I am not certain if this is what's causing the error but it looks like it when I test it.
I made the game so that whenever enemy players touch the player, the game ends and a function is called to change the game scene. This is where the error is called, whenever the scene is about to change.
"fatal error: unexpectedly found nil while unwrapping an Optional value"
here is the code for the didBegin(contact: SKPhysicsContact)
func didBegin(_ contact: SKPhysicsContact) {
var BodyOne = SKPhysicsBody()
var BodyTwo = SKPhysicsBody()
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask{
BodyOne = contact.bodyA
BodyTwo = contact.bodyB
}
else{
BodyOne = contact.bodyB
BodyTwo = contact.bodyA
}
//SHIPS TOUCH EACH OTHER CHECK
if BodyOne.categoryBitMask == NumberingPhysics.SpaceShip && BodyTwo.categoryBitMask == NumberingPhysics.LeftV{
GameOver1()
BodyTwo.node?.removeFromParent()
BodyOne.node?.removeFromParent()
}
if BodyOne.categoryBitMask == NumberingPhysics.SpaceShip && BodyTwo.categoryBitMask == NumberingPhysics.RightV{
GameOver1()
BodyOne.node?.removeFromParent()
BodyTwo.node?.removeFromParent()
//more code is under here
}
And here is the code of the game changing scene. (which works when 1 enemy touches the player but doesn't seem to when 2 or more makes contact with the player)
func GameOver1(){
ButtonAudioPlayer.stop()
removeAllChildren()
removeAllActions()
let scene = GameOver(size: self.size)
let sKView = self.view! as SKView // <----- error shows here
sKView.ignoresSiblingOrder = true
scene.scaleMode = .aspectFill
sKView.presentScene(scene)
}
Can someone please help me resolve this issue.