Search code examples
iosxcodeswiftforced-unwrapping

fatal error: unexpectedly found nil while unwrapping an Optional value for physics body contact


I can't seem to figure out which optional value it is talking about or why i am getting this error. I checked my score integer and made sure that I declared its value is 0 until it makes contact with the enemy. In the simulator the counter counts the first 4 or 5 enemies then crashes.

var score = Int? ()
var scoreLabel = UILabel ()
override func didMoveToView(view: SKView) {

scoreLabel.text = "\(score)"
scoreLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 
20))
scoreLabel.textColor = UIColor.blackColor()

score = nil
if score == nil {
    score = 0
    scoreLabel.text = "\(score!)"
}
func didBeginContact(contact: SKPhysicsContact) {

let firstBody : SKPhysicsBody = contact.bodyA
let secondBody : SKPhysicsBody = contact.bodyB

if ((firstBody.categoryBitMask == PhysicsCategory.bullet) &&  
(secondBody.categoryBitMask == PhysicsCategory.enemy) ||
(firstBody.categoryBitMask == PhysicsCategory.enemy) && 
(secondBody.categoryBitMask == PhysicsCategory.bullet)) {
 //i get the error next line            
collisionWithBullet((firstBody.node as! SKSpriteNode), 
bullet: (secondBody.node as! SKSpriteNode))
 }
}

func collisionWithBullet(enemy: SKSpriteNode, bullet: SKSpriteNode){

score? += 1
scoreLabel.text = "\(score!)"
enemy.removeFromParent ()
bullet.removeFromParent ()

}

Solution

  • Change score to

    var score = 0
    

    instead of

    var score = Int? ()
    

    and instead of this part

    score = nil
    if score == nil {
        score = 0
        scoreLabel.text = "\(score!)"
    }
    

    write only this

    scoreLabel.text = "\(score)"
    

    Edit: instead of this part

    collisionWithBullet((firstBody.node as! SKSpriteNode), 
    bullet: (secondBody.node as! SKSpriteNode))
    

    do something like this

    if let firstNode = firstBody.node as? SKSpriteNode,
     secondNode = secondBody .node as? SKSpriteNode {
    collisionWithBullet((firstNode), 
        bullet: (secondNode))
    }