2016-03-30 6 views
0

これは、どのような任意の値について話しているのかわかりません。私は自分のスコア整数をチェックし、敵と接触するまでその値が0であることを宣言したことを確認した。シミュレータでは、カウンタは最初の4つまたは5つの敵をカウントし、クラッシュします。非オプションとデフォルトとして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() 

} 
+0

Objective c、 '[enemy removeFromParent] ' –

+0

チェーンのロギングを開始します。 collisionWithBulletが呼び出されますか?もしそうなら、敵とは何か、それが呼ばれたら何が弾丸ですか? –

+0

なぜあなたは 'score'をオプションとして宣言していますか?初期値が0の場合は、それを非オプションの 'var score = 0'として宣言します。 – vadian

答えて

2

メークスコアは

var score = 0 
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() 

//が得点にnilを代入し、ゼロをチェック得点???

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

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 // score is no more optional. default score is 0 
scoreLabel.text = "\(score!)" 
enemy.removeFromParent() 
bullet.removeFromParent() 

} 
+0

助けてくれてありがとう、私は変数に整数を変更しましたが、私はまだエラーが出て、私はもはや適用できません!得点する。表示する移動でデフォルトスコアを0に設定します。 –

+0

また、score == nil {score = 0 scoreLabel.text = "(score!)"}のスコアは削除されていません。その背後にある私の理論は、nil値を作成して、それがゼロ値を持つのでクラッシュしない@jess –

関連する問題