我正在编写的代码有一个问题,每当我点击节点以外的其他位置(例如背景)时,应用程序就会崩溃。
我尝试制作 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/