Swift开发报错"Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"怎么解决?

标签: sprite-kit Swift
发布时间: 2017/12/22 14:27:13
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我目前在用sprite-kit类库来进行游戏开发,下面是两段swift代码:

let ballCategory : UInt32 = 0x1 << 1
let avoidCategory : UInt32 = 0x1 << 2
let floorCategory : UInt32 = 0x1 << 3
let pointCategory : UInt32 = 0x1 << 4
let lifeCategory : UInt32 = 0x1 << 5
import Foundation
import SpriteKit

class Floor: SKNode {
    override init() {
        super.init()

        let leftWall = SKSpriteNode(color: UIColor.brown, size: CGSize(width: 50, height: 300))
        leftWall.position = CGPoint(x: 0, y: 100)
        leftWall.physicsBody!.isDynamic = false
        leftWall.physicsBody = SKPhysicsBody(rectangleOf: leftWall.size)
        self.addChild(leftWall)

        let rightWall = SKSpriteNode(color: UIColor.brown, size: CGSize(width: 50, height: 300))
        rightWall.position = CGPoint(x: 100, y: 200)
        rightWall.physicsBody!.isDynamic = false
        rightWall.physicsBody = SKPhysicsBody(rectangleOf: rightWall.size)
        self.addChild(rightWall)

        // self.physicsBody?.affectedByGravity = false
        // self.physicsBody?.isDynamic = false

        // Set the bit mask properties
        self.physicsBody?.categoryBitMask = balloonCategory
        self.physicsBody?.contactTestBitMask = nailDropCategory | pointCategory | lifeCategory
        //self.physicsBody?.collisionBitMask = balloonCategory
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemted")
    }
}

我现在一运行上面代码就报错"Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value".

但当我把代码里的"!"替换为"?"后,程序可以正常运行,只是运行结果不是我原先设计的那样..

解决方法 1:

你可以在对象初始化前添加:

.isDynamic = false

调用:

leftWall.physicsBody!.isDynamic = false

之后:

leftWall.physicsBody = SKPhysicsBody(rectangleOf: leftWall.size)

然后同样的:

rightWall.physicsBody!.isDynamic = false
rightWall.physicsBody = SKPhysicsBody(rectangleOf: rightWall.size)

完整代码:

let leftWall = SKSpriteNode(color: UIColor.brown, size: CGSize(width: 50, height: 300))
leftWall.position = CGPoint(x: 0, y: 100)
leftWall.physicsBody = SKPhysicsBody(rectangleOf: leftWall.size)
leftWall.physicsBody!.isDynamic = false
self.addChild(leftWall)

let rightWall = SKSpriteNode(color: UIColor.brown, size: CGSize(width: 50, height: 300))
rightWall.position = CGPoint(x: 100, y: 200)
rightWall.physicsBody = SKPhysicsBody(rectangleOf: rightWall.size)
rightWall.physicsBody!.isDynamic = false
self.addChild(rightWall)


官方微信
官方QQ群
31647020