Search code examples
swiftimagesprite-kitskspritenode2d-games

SpriteKit Lots of Nodes from Same Image: Load Separately or Duplicate?


I'm programming a game in SpriteKit and am coding a section where the "level" is loaded in from a text file, placing a wall node in every spot marked by an "x" in the text file. However, if I know that there are going to be a lot of nodes, and they're all being loaded from the same "wall.png" file, is it more efficient to load the image once and then duplicate the object each time needed, or just load the image each time?

for line in lines {
  for letter in line {
    if letter == "x" {
      let wall = SKSpriteNode(imageNamed: "wall")
      self.addChild(wall)
    } else { ... }
  }
}

VS

let wall = SKSpriteNode(imageNamed: "wall")
for line in lines {
  for letter in line {
    if letter == "x" {
      self.addChild(wall.copy())
    } else { ... }
  }
}

self in this scope is a class holding the level that extends SKNode, so I'm adding walls to self and then adding that SKNode to the scene.


Solution

  • To answer your question without resorting to 3rd party support

    Go with the 2nd option (the copy option)

    This will use the same texture across multiple sprites, where as the 1st choice creates a new texture every iteration.