Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
swift 2致命错误:在展开可选值-类别名称时意外发现nil_Swift_Swift2_Categories_Child Nodes - Fatal编程技术网

swift 2致命错误:在展开可选值-类别名称时意外发现nil

swift 2致命错误:在展开可选值-类别名称时意外发现nil,swift,swift2,categories,child-nodes,Swift,Swift2,Categories,Child Nodes,在下面的代码中,我不断得到“致命错误:在展开可选值时意外发现nil” let ballCategoryName = "ball" class GameScene: SKScene, SKPhysicsContactDelegate { override func didMoveToView(view: SKView) { let borderBody = SKPhysicsBody(edgeLoopFromRect: self.frame) borderBody.

在下面的代码中,我不断得到“致命错误:在展开可选值时意外发现nil”

let ballCategoryName =  "ball"


class GameScene: SKScene, SKPhysicsContactDelegate {
    override func didMoveToView(view: SKView) {

    let borderBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
    borderBody.friction = 0
    self.physicsBody = borderBody


    let ball = childNodeWithName(ballCategoryName) as! SKSpriteNode
    ball.position = CGPointMake(self.size.width / 2, self.size.height / 2)
    ball.physicsBody?.dynamic = true
    ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.height / 2)
    ball.physicsBody!.applyImpulse(CGVector(dx: 2.0, dy: -2.0))

    self.addChild(ball)

错误出现在“let ball=childNodeWithName(ballCategoryName)as!SKSpriteNode”处,想知道是否有人可以在这里帮助我解释为什么会一直出现此错误

您应该替换此错误

let ball = childNodeWithName(ballCategoryName) as! SKSpriteNode
用这个

let ball = SKSpriteNode(imageNamed: "YOUR_IMAGE_NAME")

我还建议您阅读。

您必须将该球创建为节点。可以这样创建节点:

让ball=SKSpriteNode(ImageName:“fileimage.png”)

然后将其添加到场景中

问题是你是在无中生有地创造球。 如果尚未创建该场景,您将无法在下面找到任何内容。那孩子根本不存在

childNodeWithName(ballCategoryName)为!斯普林泰诺


问题是你在这条线上不安全地强制施法:

let ball = childNodeWithName(ballCategoryName) as! SKSpriteNode
方法
childNodeWithName()
返回精灵工具包节点或nil(
SKSpriteNode?
)。感叹号在:
as!SKSpriteNode
表示您确定此返回值不是零,并且希望将其转换为非可选的
SKSpriteNode
。您似乎遇到了一个案例,
childNodeWithName(…
返回nil,因此播放失败,您的应用程序崩溃

您可以通过多种方式打开可选的,例如,如果使用
if let
,代码将是什么样子:

if let ball = childNodeWithName(ballCategoryName) {
    ball.position = CGPointMake(self.size.width / 2, self.size.height / 2)
    ball.physicsBody?.dynamic = true
    ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.height / 2)
    ball.physicsBody!.applyImpulse(CGVector(dx: 2.0, dy: -2.0))
    self.addChild(ball) 
}
请注意,在本例中,if
childNodeWithName(ballCategoryName)
返回nil,if子句主体中的代码将根本不会运行

有关展开可选值的所有方法的非常全面的解释,请参见


或者,正如其他答案所示,您可以使用
let ball=SKSpriteNode(imagename:“something.png”)将ball实例化为SKSpriteNode的非可选实例

不确定您在这里要问什么。显然没有您要传递的具有
ballCategoryName
的子节点?@hnh我对这种类型的代码不熟悉,所以我有点困惑。需要做些什么来添加childNode?抱歉,如果不查看childNodeWithName,这听起来很愚蠢,那么很难判断发生了什么g、 可能重复的