0

I want to search my SKScene class for childNodes that begin with "spaceship". Basically I have several spaceship nodes named "spaceship1", "spaceship2", "spaceship3", etc...

However I'm not getting the syntax right. This:

self.subscript("spaceship[0-9]")

results to :

 Expected ',' separator

And this:

self.objectForKeyedSubscript("spaceship[0-9]")

Results to :

'objectForKeyedSubscript' is unavailable: use subscripting
user594883
  • 1,329
  • 2
  • 17
  • 36

2 Answers2

2

There's a better approach to this problem than assigning tags like "spaceship" + counter.

The Spaceship class

Yes, for a number of reasons you should create a Spaceship class, like this

class Spaceship: SKSpriteNode {

    init() {
        let texture = SKTexture(imageNamed: "spaceship")
        super.init(texture: texture, color: .clearColor(), size: texture.size())
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

Retrieving all the spaceships

class GameScene:SKScene {
    var spaceships: [Spaceship] {
        return self.children.flatMap { $0 as? Spaceship }
    }
}

Why a custom class is better than "numbered tags"

For several reasons

  1. You don't get crazy assigning a new tag-with-counter value to each new sprite that should act like a Spaceship
  2. You can add behaviour to your spaceship entity simply adding methods to the Spaceship class.
  3. The compiler will block you if you erroneously use another node as a spaceship
  4. You code is cleaner
Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
1

This is a great handy reference for working with Strings in Swift. http://useyourloaf.com/blog/swift-string-cheat-sheet/

As per that site

let spaceshipString = "spaceship1"
spaceshipString.hasPrefix("spaceship")    // true
spaceshipString.hasSuffix("1")    // true

With that in mind, you can just enumerate through all your nodes to find the ones with spaceship by doing the following.

 func findSpaceShipNodes() {
    self.enumerateChildNodesWithName("//*") {
        node, stop in
            if (( node.name?.hasSuffix("spaceship") ) != nil) {
              // Code for these nodes in here //
            }
    }
}
Corey F
  • 621
  • 4
  • 14