Ios 致命错误:在展开物理实体接触的可选值时意外发现nil
我似乎无法弄清楚它所说的是哪个可选值,或者为什么会出现这个错误。我检查了我的分数整数,并确保我声明它的值为0,直到它与敌人接触。在模拟器中,计数器统计前4或5个敌人,然后崩溃Ios 致命错误:在展开物理实体接触的可选值时意外发现nil,ios,xcode,swift,forced-unwrapping,Ios,Xcode,Swift,Forced Unwrapping,我似乎无法弄清楚它所说的是哪个可选值,或者为什么会出现这个错误。我检查了我的分数整数,并确保我声明它的值为0,直到它与敌人接触。在模拟器中,计数器统计前4或5个敌人,然后崩溃 var score = Int? () var scoreLabel = UILabel () override func didMoveToView(view: SKView) { scoreLabel.text = "\(score)" scoreLabel = UILabel(frame: CGRect(x: 0,
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 ()
}
把分数改为
var score = 0
而不是
var score = Int? ()
而不是这一部分
score = nil
if score == nil {
score = 0
scoreLabel.text = "\(score!)"
}
collisionWithBullet((firstBody.node as! SKSpriteNode),
bullet: (secondBody.node as! SKSpriteNode))
只写这个
scoreLabel.text = "\(score)"
编辑:
而不是这部分
score = nil
if score == nil {
score = 0
scoreLabel.text = "\(score!)"
}
collisionWithBullet((firstBody.node as! SKSpriteNode),
bullet: (secondBody.node as! SKSpriteNode))
做这样的事
if let firstNode = firstBody.node as? SKSpriteNode,
secondNode = secondBody .node as? SKSpriteNode {
collisionWithBullet((firstNode),
bullet: (secondNode))
}
谢谢你的帮助!我以为你的建议奏效了,我几乎高兴得流下了眼泪,但崩溃的时间比平时更长,它成功地冲向了9个敌人,然后又冲向了同一条线路(虽然它不会很快崩溃,所以这有点奇怪,它直到10点左右才会崩溃@roee84没问题。它现在崩溃在哪里?同一行和同一个错误,我认为我的分数没有问题,因为我只是//'d出了我的“score+=1 scoreLabel.text=“(score)”在我的collision with bullet方法中定义,我仍然在collisionWithBullet((firstBody.node as!SKSpriteNode),bullet:(secondBody.node as!SKSpriteNode))行上得到错误。我想这是因为我的“as!”声明但我想不出其他解决方案它奏效了!我到97只是为了绝对确定!你是摇滚明星。我会在我的另一个帐户上投票支持你的答案。我不想在我的OG帐户上问这个问题,因为我知道人们会反对这个问题哈哈@roee84