swiftsprite-kit

How to change a global int in SpriteKit with Swift?


I'm coding a similar game to 4 images 1 word. I want that when I'm for example at level 5 and I close the Game and delete it out of my history, then go back to the game again and press Play I can resume at level 5. I tried that with a global Variable(LevelNumber) which is a int and has the value of 1 that means it is above the classLevel1: Skscene{ :

var levelNumber = 1
class Level1: SKScene {

In the Win function of level 1 I put the value of levelNumber to 2 (because you finished Level 1) and save that:

func Win() {
    levelNumber == 2
    NSUserDefaults.standardUserDefaults().setInteger(levelNumber, forKey: "levelNumber")
}

*edit In the MainMenu Scene I said:

 override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    
    if levelNumber == 1 {
    let Level = Level1(size: self.size)
    Level.scaleMode = scaleMode
    let transition = SKTransition.fadeWithDuration(0.5)
    self.view?.presentScene(Level, transition: transition)
    }
    
    else if levelNumber == 2{
        let Level = Level2(size: self.size)
        Level.scaleMode = scaleMode
        let transition = SKTransition.fadeWithDuration(0.5)
        self.view?.presentScene(Level, transition: transition)
    }
    
    else if levelNumber == 3 {
        let Level = Level3(size: self.size)
        Level.scaleMode = scaleMode
        let transition = SKTransition.fadeWithDuration(0.5)
        self.view?.presentScene(Level, transition: transition)
    }

And so on for all the levels.

Heres the code in the AppDelegate.swift

import UIKit

@UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?
var oldScore : Int = NSUserDefaults.standardUserDefaults().integerForKey("oldScore")
var oldlevelNumber : Int = NSUserDefaults.standardUserDefaults().integerForKey("oldlevelNumber")

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.
    Score += oldScore
    levelNumber += oldlevelNumber
    return true
}

func applicationWillTerminate(application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.

    NSUserDefaults.standardUserDefaults().setInteger(Score, forKey: "oldScore")
    NSUserDefaults.standardUserDefaults().synchronize()
    NSUserDefaults.standardUserDefaults().setInteger(levelNumber, forKey: "oldlevelNumber")
    NSUserDefaults.standardUserDefaults().synchronize()
}

But for some reason when I press Play, go to Level 1(not calling the win function), then restart the game and press Play I go to Level 2 without even Winning Level 1, why?


Solution

  • In your Win function, set your variable like this:

    levelNumber = 2
    

    Instead of

    levelNumber == 2