swift - 如何防止点击节点时崩溃

标签 swift xcode sprite-kit

我正在编写的代码有一个问题,每当我点击节点以外的其他位置(例如背景)时,应用程序就会崩溃。

我尝试制作 if let 语句,但它说我无法将 SKnode 向下转换为更可选的类型 SKSpriteNode。 我还尝试过 if node.contains(position of touch)

 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first
    if let touchLocation = touch?.location(in: self) {
    let selectedNode = nodes(at: touchLocation)[0] as! SKSpriteNode

        activeObject = selectedNode
        storedData = Array(activeObject.name!)
        let platformStoredInt = storedData[2]
        storedPlatform = Int(platformStoredInt.unicodeScalars.first!.value - Unicode.Scalar("0")!.value)

        }
    }

点击除 SKSpriteNode 之外的任何被视为对象的对象都会产生 SIGABRT。

最佳答案

应用程序崩溃,因为您强制解包此行中的值:

让 selectedNode = 节点(at: touchLocation)[0] 为! SKSpriteNode

因此,请使用:

if let selectedNode = nodes(at: touchLocation)[0] as? SKSpriteNode {

  activeObject = selectedNode
  storedData = Array(activeObject.name!)
  let platformStoredInt = storedData[2]
   storedPlatform = Int(platformStoredInt.unicodeScalars.first!.value - Unicode.Scalar("0")!.value)

}

始终尽量避免用力展开(如!)。使用Optional Chaining相反。

Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil.

关于swift - 如何防止点击节点时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56150758/

相关文章:

ios - 使用 map 迭代时排除数组中的元素

swift - 根据 titleLabel 的长度调整 UIButton 的大小

ios - swift 中的 AVfoundation - 如何包含多种文件类型

ios - class is not-key value coding compliant error 但 Storyboard 中的一切都是正确的

ios - 静态单元格不显示在模拟器中

swift - iPad Retina 的 SkTextureAtlas 动画?

swift - iCloud keyValue 使我的游戏崩溃

sprite-kit - 来自 SKTextureAtlas 的 SKTexture 是否支持 mipmap 功能?

ios - 当应用程序处于后台模式时,如何获取错过的 CloudKit 通知?

ios - 为 Instagram 和 Vine 等 iOS 应用程序注册添加视频背景