You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift SpriteKit代码报错:[SKNode]类型无name成员,请求协助

Fixing the '[SKNode]' has no member 'name' Error in Your touchesBegan Function

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:23:45