Search code examples
iosswiftsprite-kitskspritenode

How can I get the number of skspritenodes in a scene?


I want to find out what the number of nodes is in a scene. For example, I want to create an if statement so that if the number of nodes in the scene is 0 or any other number, I would call a function.

This is what i have done but it only calls the function the first time children.count is 0 but ignores the other times.

I am not removing or adding any sprite nodes anywhere else in my code.

func dot(){
    var dotTexture = SKTexture (imageNamed: "dot")
    dotTexture.filteringMode = SKTextureFilteringMode.Nearest

    var dot = SKSpriteNode(texture: dotTexture)
    dot.setScale(0.5)
    dot.position = CGPoint(x: self.frame.size.width * 0.5 , y: self.frame.size.height * 1.1)

    dot.physicsBody = SKPhysicsBody (circleOfRadius: dot.size.height/2.0)
    dot.physicsBody?.dynamic = true
    dot.physicsBody?.allowsRotation = false

    self.addChild(dot)


    println("done")

}

 override func update(currentTime: CFTimeInterval) {
    /* Called before each frame is rendered */
    if children.count == 0 {
        dot()

        println("dot")
    }
}

Solution

  • if you're doing this inside the scene itself you can do

    if (self.children.count == x) {
       yourFunction() //call your function
    }
    

    or

    if (children.count == x) {
        yourFunction() //call your function
    }
    

    in response to your comment:

    there's an update method that runs every frame in sprite kit. Use it like this:

    override func update(currentTime: CFTimeInterval) {
        /* Called before each frame is rendered */
        if (children.count == x) {
            yourFunction() //call your function
        }
    }