Astrum Astrum - 3 months ago 10
Swift Question

Trying to change an SKSpriteNode image using a variable

So I recently started using a struct to hold variables that define my achievement so that it makes it easier to access. as seen below:

struct Achieve {

var aName:String = ""
var aDes:String = ""
var aImage:String = ""
var aAmount:Int = 0
var aRequired:Int = 0

}


So I defined a variable called 'Ach1' like so:

var Ach1 = Achieve(aName: "No. Games", aDes: "Games Played", aImage: "locked", aAmount: 0, aRequired: 10)


and then I created an SKSpriteNode using the function below:

func generateShopItems (location: CGPoint, page:SKSpriteNode, tex: String) -> SKSpriteNode {

let node = SKSpriteNode(imageNamed: tex)
node.position = location
page.addChild(node)
return node
}


Then I used the Ach1 variable's aImage property as the tex string when defining the SKSpritenode in another function like below

Achievements.append(generateShopItems(CGPointMake(-120, 200), page:(page1ScrollView), tex: Ach1.aImage))


The texture comes out fine when the game is run for the first time but i can't get the image to change when I change the Ach1 variables aImage property in my touches method it just stays the same.

} else if (node == Achievements[7]) {

Ach1.aImage = "diamondicon"
print("working")

}


I need to be able to change the image of the SKSpriteNode while the game is being played. Can someone please tell me what I am doing wrong?

EDIT

var Ach1 = Achieve(node: SKSpriteNode?, aName: "No. Games", aDes: "Games Played", aImage: "locked", aAmount: 0, aRequired: 10)

Answer

This is the solution that comes to my mind first. It may not be the best, but it's not bad either.

In your Achieve struct, add a property called node:

var node: SKSpriteNode?

And change the aImage property to look something like this:

var aImage: String = "" {
    didSet {
        node?.texture = SKTexture(imageNamed: aImage)
    }
}

Now when you generate the nodes, replace this:

Achievements.append(generateShopItems(CGPointMake(-120, 200), 
    page:(page1ScrollView), tex: Ach1.aImage))

with this

var node = generateShopItems(CGPointMake(-120, 200), 
    page:(page1ScrollView), tex: Ach1.aImage)
Achievements.append(node)
Ach1.node = node

Now when you change the aImage property of Ach1, the node's texture should change as well.