Felix F. Felix F. - 7 months ago 25
Swift Question

How to update Label instead overwrite?

I'm stuck with a little

SpriteKit
game and got this inside my
projectileHit
function, and instead of updating the
label
to the current number of
monstersDestroyed
, it just overwrites it, so first a 1, then a 2 on top of the one, then a 3 and so on.

How do I make it "delete" the previous number first and then fill in the next one?

func projectileDidCollideWithMonster(projectile:SKSpriteNode, monster:SKSpriteNode) {
print("Hit")
projectile.removeFromParent()
monster.removeFromParent()
monstersDestroyed++
let myLabel = SKLabelNode(fontNamed:"Chalkduster")
self.addChild(myLabel)
myLabel.text = String(monstersDestroyed)

Answer

Move label outside the function, so it is created only once, and only change label text when collision happened.

class GameScene: SKScene {
   var monstersDestroyed = 0
   let myLabel = SKLabelNode(fontNamed:"Chalkduster")

   override func didMoveToView(view: SKView) {
       self.addChild(myLabel)
   }

   func projectileDidCollideWithMonster(projectile:SKSpriteNode, monster:SKSpriteNode) {
       monstersDestroyed++
       myLabel.text = String(monstersDestroyed)
   }
}