Search code examples
xcodeswiftaddchild

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]))        
}

I found this on a tutorial website, and I'm planning on modifying it to some extent. However, when I try to run the code, it presents me with a "Use of unresolved identifier 'addChild'". I'm not sure how to fix this.


Solution

  • Your function seems to be outside of the class, which causes the method addChild to not be found by the compiler.

    You need to include all relevant methods of a class in between the class parentheses, in the same file is not good enough.