0

I' like to doe something like this :

for i in 0...3 {
let skspritenode\(i) = SKSpriteNode(imageNamed: "Layer_\(i)")
self.addChild(skspritenode\(i))
}

that doesn't work because my skspritenode(i) is a let and not a string and I have tried this:

for i in 0...3 {
let skspritenode = SKSpriteNode(imageNamed: "Layer_\(i)")
self.addchild(skspritenode)
}

which doesn't work because skspritenode already has a parent.

Is there a way of doing this in a for loop or do i have to declare each let separately? Thank you in advanced

1 Answer 1

1

Why would you need to name each node differently? skspritenode variable is scoped in for loop, thus the following code should work just fine:

for i in 0...3 {
  let skspritenode = SKSpriteNode(imageNamed: "Layer_\(i)")
  self.addchild(skspritenode)
}

Your point

which doesn't work because skspritenode already has a parent

is incorrect, since you're creating new SKSpriteNode on each iteration.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.