在解包一个Optional值时发现nil - spriteKit

时间:2014-07-27 16:48:52

标签: ios swift sprite-kit

我的触摸事件功能有问题,它说“致命错误:在解开可选值时意外发现nil” 我试图点击标签下的节点。

override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {
    let location: CGPoint = touches.anyObject().locationInNode(self)
    let nodes: NSArray = nodesAtPoint(location)

       for node: AnyObject in nodes {
           println("node name : " + node.name) // Error here
       }

错误:

fatal error: unexpectedly found nil while unwrapping an Optional value

控制台输出:

node name : myLabel
node name : MyNode

问题只出现在我的设备上,它在模拟器上运行得很好。 Xcode 6.4,SDK 8.0,目标7.0,设备7.1.2

已编辑:

场景中我唯一的精灵代码。点击它时得到了解开的错误。

   var score: SKLabelNode = SKLabelNode()
    score.text = "0"
    score.name = "scoreLabel"
    score.fontName = "Chalkduster"
    score.fontSize = 42
    score.zPosition = 100
    score.fontColor = UIColor.redColor()
    score.position = CGPointMake(CGRectGetWidth(self.frame) - 50, CGRectGetHeight(self.frame) - 40)
    self.addChild(score)

1 个答案:

答案 0 :(得分:0)

你必须尝试设备:

override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {
    let location: CGPoint = touches.anyObject().locationInNode(self)
    let nodes: NSArray = nodesAtPoint(location)

       for node: AnyObject in nodes {
           let strName = node.name as string
           println("node name : \(strName)") 
       }