mamaz
mamaz

Reputation: 1

SKSpriteNode in array change image

I put few SKSpriteNode in SKSPriteNode Array in didMove(to view:SKView) using

enumerateChildNodes(withName: "//*") { (node, stop) in
    if let spriteNode = node as? SKSpriteNode{
            if let nodeName = node.name{
                if nodeName.hasSuffix("Button"){
                    self.buttons.append(spriteNode)

                }
            }
        }
    }

and now using a result from my NSCoding I would like change my buttons image

    for node in self.buttons{
        if let name = node.name{
            if name.hasSuffix("Button"){
                let letter = name.replacingOccurrences(of: "Button", with: "", options: .regularExpression)
                if let number = self.gameResult[letter]{
                    switch number{
                    case 1:
                        node = SKSpriteNode(imageNamed: "\(letter)Button-Bronze")
                    case 2:
                        node = SKSpriteNode(imageNamed: "\(letter)Button-Silver")
                    case 3:
                        node = SKSpriteNode(imageNamed: "\(letter)Button-Gold")
                    default:
                        node = SKSpriteNode(imageNamed: "\(letter)Button-Bronze")
                    }
                }
            }
        }
    }

It appears that all node in array are let and I cannot change images in my SKSpritNode buttons.

How can I do that?

Could you please help me?

Upvotes: 0

Views: 54

Answers (1)

Steve Ives
Steve Ives

Reputation: 8134

Any time you enumerate over a collection (for node in array etc), the property used for enumerating is automatically a let. The whole collection itself is also immutable, because changing the collection whilst enumerating over it could have unforeseen consequences.

copy the nodes to a new array, changing the properties of the nodes as you desire and then swap the arrays afterwards.

Is there a reason why you can't change the node's images via enumeratechildNodes(withName:?

Upvotes: 1

Related Questions