Search code examples
xcodeswiftsprite-kitscene

Xcode Swift pass func to GameOverScene


I need some help with my Highscore. In my GameScene.swift I set the Highscore functions but the problem is that i would like to show the Highscore in my GameOverScene.swift. Here is what I created in the GameScene.swift:

func operateOnScore(score:NSInteger) {
    if getBestScore() < GameScene.score {
        setBestScore(GameScene.score)
    }
}

func setBestScore(score:NSInteger){

    let userDefaults = NSUserDefaults.standardUserDefaults()

    userDefaults.setObject(score, forKey: "bestscore")

    userDefaults.synchronize()
}

func getBestScore() -> NSInteger {
    let userDefaults = NSUserDefaults.standardUserDefaults()
    return userDefaults.objectForKey("bestscore")!.integerValue
    }

This works pretty well if i show it in the GameScene.swift but now I'd like to show my Highscore in my GameOverScene.swift. I found something on Apple's development homepage but it don't work. I also set this struct to my GameScene.swift:

struct HS {
func  Showbest() {

    let bestFinalText = SKLabelNode(fontNamed: "04b_19")
    bestFinalText.fontSize = 20
    bestFinalText.zPosition = 120
    bestFinalText.fontColor = UIColor.blackColor()
    bestFinalText.position = CGPointMake( CGRectGetMidX( self.frame )+90,CGRectGetMidY( self.frame )-10)
    bestFinalText.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.Right
    bestFinalText.text = NSString(format: "%d", self.getBestScore()) as String
    self.addChild(bestFinalText)
}

}

Have somebody an idea how I can pass my function to my GameOverScene?


Solution

  • You don't need to make a struct, simply you could create a new file called for example "Utils.swift" without class declaration :

    Utils.swift (as you can see there isn't class declaration):

    import UIKit
    import SpriteKit
    
    func getBestScore() -> NSInteger {
       let userDefaults = NSUserDefaults.standardUserDefaults()
       return userDefaults.objectForKey("bestscore")!.integerValue
    }
    
    func showBest()->SKLabelNode {
        let bestFinalText = SKLabelNode(fontNamed: "04b_19")
        bestFinalText.fontSize = 20
        bestFinalText.zPosition = 120
        bestFinalText.fontColor = UIColor.blackColor()
        bestFinalText.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.Right
        return bestFinalText
    }
    

    In Swift there is no need to import classes, so simply when you are in your GameOverScene.swift call these functions like this for example:

    let scoreLabel = showBest()
    scoreLabel.text = "points are: \(getBestScore())"
    scoreLabel.position = CGPointMake( CGRectGetMidX( self.frame )+90,CGRectGetMidY( self.frame )-10)
    self.addChild(scoreLabel)