Swift SpriteKit代码报错:[SKNode]类型无name成员,请求协助
Hey there! Let's break down what's going wrong here and fix that error quickly.
The Root Cause
The line let nodeITapped = self.nodes(at: pointOfTouch) is the culprit here. The nodes(at:) method in SpriteKit doesn't return a single SKNode — it returns an array of SKNodes ([SKNode]). This is because multiple nodes can overlap at the same touch point (think of a button under a semi-transparent overlay, for example). Arrays don't have a name property, which is exactly why you're seeing that error.
Solutions
Here are two common ways to fix this depending on what you need:
1. Target the Topmost Node (Most Common Use Case)
If you just care about the node that's visually on top (the first one in the array), use first to grab it, and use optional binding to avoid crashes if no nodes are tapped:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches { let pointOfTouch = touch.location(in: self) // Grab the first (topmost) node at the touch point if let nodeITapped = self.nodes(at: pointOfTouch).first, nodeITapped.name == "startButton" { let sceneToMoveTo = GameScene(size: self.size) sceneToMoveTo.scaleMode = self.scaleMode // Add your scene transition code here, e.g.: self.view?.presentScene(sceneToMoveTo, transition: .fade(withDuration: 0.5)) } } }
2. Check if Any Node in the Array Has the Target Name
If you need to detect if any node at the touch point has the name "startButton" (regardless of position in the stack), use contains(where:):
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches { let pointOfTouch = touch.location(in: self) let tappedNodes = self.nodes(at: pointOfTouch) // Check if any node in the array matches the name if tappedNodes.contains(where: { $0.name == "startButton" }) { let sceneToMoveTo = GameScene(size: self.size) sceneToMoveTo.scaleMode = self.scaleMode self.view?.presentScene(sceneToMoveTo, transition: .fade(withDuration: 0.5)) } } }
Quick Note
Remember that nodes(at:) returns nodes in order from the topmost (highest zPosition) to the bottommost (lowest zPosition). So using first will always get you the node the user actually sees and taps on.
内容的提问来源于stack exchange,提问作者mohammad ali

