Chapter 14 Saving and Loading

I keep getting an error the player node is always nil I cannot figure this out for the life of me.

Is anyone else getting this error ?? But when I put addchild(player) instead it has both characters on the scene…very confused.

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)

background = childNode(withName: "background layer") as! SKTileMapNode

obstaclesTileMap = childNode(withName: "obstacles") as? SKTileMapNode

if let timeLimit = userData?.object(forKey: "timeLimit") as? Int {
  
  self.timeLimit = timeLimit
  
}

let savedGameState = aDecoder.decodeInteger(forKey: "Scene.gameState")
if let gameState = GameState(rawValue: savedGameState), gameState == .pause {
  
  self.gameState = gameState
  firebugCount = aDecoder.decodeInteger(forKey: "Scene.firebugCount")
  elapsedTime = aDecoder.decodeInteger(forKey: "Scene.elapsedTime")
  currentLevel = aDecoder.decodeInteger(forKey: "Scene.currentLevel")
  
  
  player = childNode(withName: "Player") as! Player
  
  hud = camera!.childNode(withName: "HUD") as! HUD
  bugsNode = childNode(withName: "Bugs")!
  bugsprayTileMap = childNode(withName: "Bugspray") as? SKTileMapNode
  
}

addObservers()

}

Sometimes these are quite hard to work out, and unfortunately impossible from just that code extract.

I note that you are referring to your background as being called "background layer". Is that correct? Is that what you’ve called it in the scene editor?

Is the error when you have a saved game state? You can check this by doing a print statement after assigning the player. Whatever you print will show up in the debug console.

Have you set up Player with the encoding?

Have you checked that the supplied final code works? You could also compare your code to the final code. (When I’m tracking stuff down like this, I gradually replace files until it works. Then I can find out which file fixed it and narrow down from there.)

hey thanks for the reply !! you gave me an idea to look for the name of the child in my Player.swift class.

Turned out I did this

Player.swift had

name = “player”

and in game scene i was calling

player = childNode(withName: “Player”) as! Player

the error game from the P not being capital.

Thank you so much for your help and reply !

1 Like