I've got a variable in my GameScene, it's score variable, and it's being displayed on screen with SKLabelNode.
Everytime time there is a collision, 1 is being added to score, which is being transfered as a string to the SKLabelNode, and then updated on screen.
Problem is, when I call it from my GameOverScene (scene where the final score is being displayed along with "game over"), I get first value of score, which is 0. Like GameOverScene is reading variable, but not the updated one. How to get the updated variable? Can anyone help?
Code:
class GameScene: SKScene, SKPhysicsContactDelegate {
// S C O R E !
var score = 0
var scoreText: String = ""
var scoreOnScreen = SKLabelNode()
...
override func didMoveToView(view: SKView) {
// S C O R E
scoreOnScreen.position = CGPoint(x: size.width / 2, y: size.height * 0.8)
scoreText = String(score)
scoreOnScreen.text = scoreText
when collision takes place, score get's +1
func bulletDidCollideWithEnemy(enemy: SKSpriteNode, bullet: SKSpriteNode) {
score++
scoreText = String(score)
scoreOnScreen.text = scoreText
and then, the GameOverScene:
import SpriteKit
import UIKit
class GameOverScene: SKScene {
let GameSceneInstance = GameScene()
let bgImage = SKSpriteNode(imageNamed: "background")
let afraidLogo = SKSpriteNode(imageNamed: "gameoverlogo")
var gameOverLabel = SKLabelNode()
override func didMoveToView(view: SKView) {
GameSceneInstance.scoreOnScreen.text = String(GameSceneInstance.score)
bgImage.position = CGPoint(x: size.width / 2, y: size.height / 2)
bgImage.setScale(0.75)
addChild(bgImage)
afraidLogo.position = CGPoint(x: size.width / 2, y: size.height / 2)
afraidLogo.setScale(0.50)
addChild(afraidLogo)
gameOverLabel.fontSize = 40
gameOverLabel.fontColor = SKColor.whiteColor()
gameOverLabel.text = "score: \(GameSceneInstance.scoreOnScreen.text)"
gameOverLabel.position = CGPointMake(self.size.width/2, 2.0 / 3.0 * self.size.height);
addChild(gameOverLabel)
}
I bet it's just a simple issue with the code. Appreciate any help.
I figured it out with some help from a reddit guy with a nickname Jasamer. Guy rocks.
Here's what I've changed:
when the scene is being changed
let scene = GameOverScene(size: skView.bounds.size)
I added:
scene.gameScene = self
scene.score = score
and then, the GameOverScene:
class GameOverScene: SKScene {
var gameScene = GameScene()
override func didMoveToView(view: SKView) {
gameOverLabel.text = "score: \(gameScene.score)"
and it works.
The main problem I think was not setting scene.GameScene = self
.
I hope this helps someone someday.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With