Swift: 使用未解析的标识符 'addChild'

Swift: Use of unresolved identifier 'addChild'

import SpriteKit

class GameScene: SKScene 
{    
    let player = SKSpriteNode(imageNamed: "Gun")

    override func didMoveToView(view: SKView) 
    {    
        backgroundColor = SKColor.whiteColor()    
        player.position = CGPoint(x: size.width * 0.1, y: size.height * 0.5)
        addChild(player)
    }
}

func random() -> CGFloat 
{
    return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
}

func random(#min: CGFloat, max: CGFloat) -> CGFloat 
{
    return random() * (max - min) + min
}

func addMonster() 
{        
    let monster = SKSpriteNode(imageNamed: "monster")        
    let actualY = random(min: monster.size.height/2, monster.size.height - monster.size.height/2)

    monster.position = CGPoint(x: monster.size.width + monster.size.width/2, y: actualY)

    // Here's the error:
    addChild(monster)

    let actualDuration = random(min: CGFloat(2.0), CGFloat(4.0))        
    let actionMove = SKAction.moveTo(CGPoint(x: -monster.size.width/2, y: actualY), duration: NSTimeInterval(actualDuration))
    let actionMoveDone = SKAction.removeFromParent()

    monster.runAction(SKAction.sequence([actionMove, actionMoveDone]))        
}

我在一个教程网站上找到了这个,我打算对其进行一定程度的修改。但是,当我尝试 运行 代码时,它会向我显示 "Use of unresolved identifier 'addChild'"。我不确定如何解决这个问题。

您的函数似乎在 class 之外,这导致编译器找不到方法 addChild

您需要在 class 括号之间包含一个 class 的所有相关方法,在同一个文件中是不够的。