Questions Questions - 1 month ago 10
Swift Question

Randomly Generated SKTexture to multiple SKNodes Giving The Same Output

I am using the following code to generate a random SKTexture and assign it to an SKSpriteNode.

var spriteTexture = [(SKTexture, String)]()

spriteTexture.append((SKTexture(imageNamed: "red"), "red"))
spriteTexture.append((SKTexture(imageNamed: "blue"), "blue"))
spriteTexture.append((SKTexture(imageNamed: "green"), "green"))

let rand = Int(arc4random_uniform(UInt32(spriteTexture.count)))
let chosenSprite = spriteTexture[rand].0 as SKTexture
let spriteName = spriteTexture[rand].1
let spriteSkin = chosenSprite


I assign the SKTexture to the SKSpriteNode using this code.

let Sprite1 = SKSpriteNode(texture: spriteSkin)
let Sprite2 = SKSpriteNode(texture: spriteSkin)


The code works fine and always generates a random image...however, Sprite1 and Sprite2 always have the same random image!

How can I make sure that each SKSpriteNode gets its own "random" image?

Thanks :D

Answer

Your skin is equal because you got only one random number.

func getRandomSkin () -> SKTexture {
    let rand = Int(arc4random_uniform(UInt32(spriteTexture.count)))
    let chosenSprite = spriteTexture[rand].0 as SKTexture
    return chosenSprite 
}

 let randomSkin1 = getRandomSkin () 
 let randomSkin2 = getRandomSkin () 

 let sprite1 = SKSpriteNode(texture: randomSkin1)
 let sprite2 = SKSpriteNode(texture: randomSkin2)

UPDATE If you want the name:

func getRandomSkinNode () -> SKSpriteNode {
    let rand = Int(arc4random_uniform(UInt32(spriteTexture.count)))
    let chosenSprite = spriteTexture[rand].0 as SKTexture
    let spriteName = spriteTexture[rand].1
    let spriteNode = SKSpriteNode(texture: chosenSprite)
    spriteNode.name = spriteName 
    return spriteNode
}

 let sprite1 = getRandomSkinNode()
 let sprite2 = getRandomSkinNode()