Milouvert
Milouvert

Reputation: 3

Fatal error created while trying to use removeAllChildren() and removeAllActions() before reloading a SKScene

this is my first question on Stack Overflow, so yeah.. Anyway, I tried to create a "reload" button for my SKScene. To do so, I created a new SKSpriteNode subclass called "EDSpriteNodeButton". Into this subclass file, I created a protocol, so I can access a method from my scene. Here's my protocol code :

protocol EDSpriteNodeButtonDelegate: AnyObject {
func spriteNodeButtonPressed(_ button: EDSpriteNodeButton)
}    

I then went back to my level scene and added my custom delegate...

class Level1Scene: SKScene, SKPhysicsContactDelegate, EDSpriteNodeButtonDelegate {

I then set my SKSpriteNode(which I'm using as my button)'s class to "EDSpriteNodeButton", made a var from my button, then made it a childNode and called my method at the bottom of my class.

var reloadSceneButton = EDSpriteNodeButton()

reloadSceneButton = self.childNode(withName: "reloadSceneButton") as! EDSpriteNodeButton
reloadSceneButton.isUserInteractionEnabled = true
reloadSceneButton.delegate = self

func reloadSceneRequested(_ button: EDSpriteNodeButton) {
    self.removeAllChildren()
    self.removeAllActions()
    self.scaleMode = .aspectFill
    self.scene?.view?.presentScene(self, transition: SKTransition.fade(withDuration: 1.0))

But when reloadSceneRequested() is called, I get a fatal error:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value.

Does anyone know how to get my SKScene to reload completely (Like if it was the first time it was running)?

Upvotes: 0

Views: 83

Answers (1)

Dipika
Dipika

Reputation: 1127

  1. check return type of childNode(withName: ) method, surely it is not returning EDSpriteNodeButton type and you are forcefully casting(as!) it in EDSpriteNodeButton type.
  2. Don't forcefully casting the result of childNode(withName: ) instead put a guard there.

Upvotes: 1

Related Questions