-2

I am trying to make a 'money' value show on 3 different scenes, and it is showing on the GameScene but not on the GameOverScene or the ShopScene.

this is the relevant code of the GameScene that is working:

 func adjustMoney(by points: Int){
    var money = UserDefaults().integer(forKey: "moneyscore")
    money += points
    MoneyLabel.text = "Money = " + UserDefaults().integer(forKey: "moneyscore").description
    UserDefaults().set(money, forKey: "moneyscore")
}

func projectileDidCollideWithMonster(projectile: SKSpriteNode, monster: SKSpriteNode) {
    print("Hit")
    projectile.removeFromParent()
    monster.removeFromParent()
    monstersDestroyed += 1
    adjustScore(by: 1)
    adjustMoney(by: 2)

and this is the total code in the other scenes (there is just the ShopScene as it is the same in the other):

import Foundation
import SpriteKit

var welcomeLabel: SKLabelNode!
class ShopScene: SKScene {

var background = SKSpriteNode(imageNamed: "background")

override func didMove(to view: SKView) {
    background.zPosition = -1
    background.position = CGPoint(x: frame.size.width / 2, y: frame.size.height / 2)
    addChild(background)       welcomeLabel = SKLabelNode(fontNamed: "Chalkduster")
    welcomeLabel.text = "Welcome to the shop!"
    welcomeLabel.fontSize = 40
    welcomeLabel.fontColor = SKColor.black
    welcomeLabel.position = CGPoint(x: size.width/2, y: size.height/1.2)
    addChild(welcomeLabel)

    MoneyLabel = SKLabelNode(fontNamed: "Chalkduster")
    MoneyLabel.text = "Money = \(money)"
    MoneyLabel.fontSize = 20
    MoneyLabel.fontColor = SKColor.black
    MoneyLabel.position = CGPoint(x: size.width/6.2, y: size.height/1.35)
    addChild(MoneyLabel)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?)  {

    let gameScene = GameScene(size: self.size)
    gameScene.scaleMode = .aspectFill

    self.view?.presentScene(gameScene, transition: SKTransition.doorsCloseHorizontal(withDuration: 1.0))
    }
}

However it only says money = 0

---- I'm not sure if it is of any relevance but before my 'projectile' and 'monster' first collide each game all my values of high score and score and money are 0 then they go back to their saved values, apart from score obviously that goes to 0. Score is the only value that isn't saved and that does move across to the GameOverScene.

0xInfection
  • 2,676
  • 1
  • 19
  • 34
camer0n
  • 1
  • 2

1 Answers1

-1

You need to access UserDefaults().integer(forKey: "moneyscore") to use this in both the GameOverScene or the ShopScene class as you are updating userdefaults value(money).

This is actually for your specific case only. On the other hand, if you are interested to pass data in different classes(you can mention them as screens if they have views), you can follow different methodologies. You can follow this link for references.

shakil080
  • 351
  • 2
  • 5