Im creating a game and i have created and integer which keeps track of the number of enemies killed, however i can not get the sklabel on the UI to update. no matter how many enemies the integer kept displaying 0. Here are some of the methods i have tried
class GameScene: SKScene, SKPhysicsContactDelegate {
var Enemy1KillCounter = 0
var Enemy1KillCounterLabel = SKLabelNode ()
override func didMoveToView(view: SKView) {
createEnemyKilledLabel()
}
func createEnemyKilledLabel() {
Enemy1KillCounterLabel.fontSize = 65
Enemy1KillCounterLabel.fontColor = SKColor .blackColor()
Enemy1KillCounterLabel.position = CGPointMake(400, 400)
self.addChild(Enemy1KillCounterLabel)
}
func updateEnemy1KillCounter() {
Enemy1KillCounter += 1
Enemy1KillCounterLabel.text = "\(Enemy1KillCounter)"
score = score + 15
//enemy1Killed = true I had tried Boolean values as well
print("updateEnemy1KillCounter")
}
//this method is called in my enemy1 class when its "killed"
func Enemy1DieG () {
updateEnemy1KillCounter()
}
}
i have also tried using the update method with boolean values implicated multiple different ways but none worked.
override func update(currentTime: CFTimeInterval) {
if enemy1Killed {Enemy1KillCounter += 1}
Enemy1KillCounterLabel.text = "\(Enemy1KillCounter)"
}
here is my enemy class and where i am calling the "enemy1DieG" method
I call the hit method in a contact method but i know that is not the issue because when the enemy is is "killed" when it is hit 5x's so the enemy1die and killCounter methods are being called
class Enemy1: SKNode {
var Enemy1Health:Int = 50
func hit() ->Bool {
Enemy1Health -= 10
Bullet1GoAway = true
if ( Enemy1Health <= 0 ) {
Enemy1Die()
return true
} else {
return false
}
}
func Enemy1Die () {
self.removeFromParent()
Enemy1KillCounter()
}
func Enemy1KillCounter (){
GameScene().Enemy1DieG()
}
}
its so weird all of the methods are being called i used print values on each method to make sure but my integer is not updating in my UI it just keeps displaying 0. This is probably such an easy answer and I keep missing it, if anybody can help that'd be awesome.
When inside Enemy1KillCounter()
you write
GameScene().Enemy1DieG()
you are NOT using the GameScene shown on the screen.
Instead you are temporarily creating a new empty screen, invoking Enemy1DieG()
on it and they destroying it.
Please replace this
func Enemy1KillCounter (){
GameScene().Enemy1DieG()
}
with this
func Enemy1KillCounter() {
guard let gameScene = self.scene as? GameScene
else { fatalError("Current node is not inside a GameScene") }
gameScene.Enemy1DieG()
}