2

I found this small and elegant way to switch between two (or probably more) scenes in SpriteKit using Swift:

class GameScene: SKScene {

    override func didMove(to view: SKView) {
        self.backgroundColor = SKColor.blue
        //initialize the scene
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?){
        let newScene = PrefScene()
        newScene.scaleMode = .aspectFill
        self.view?.presentScene(newScene, transition: SKTransition.crossFade(withDuration: 3))
    }
}

The present scene creates the new scene and sends this to it's view. However, doing it this way creates a new scene object every time there's a transition. Will this lead to memory leakage in the long run?

Oortone
  • 175
  • 7
  • 1
    there would be many cases where memory issue can arise. If your **GameScene** contains other nodes(like Player sprites), and after transition they are not deallocated then memory issue may emerged. If your scenes are simple as you posted here, it might not lead any leakage issue so far. you may check [this](https://stackoverflow.com/questions/49118097/memory-leak-when-presenting-spritekit-scenes) post for some important info – Imrul Kayes May 21 '18 at 08:20
  • one trick I like doing is overrideing deinit on game scene, and placing a message telling me that the game scene did in fact, deinit – Knight0fDragon May 21 '18 at 13:05
  • Thanks KnightOfDragon, that's definitely a thing I will do. – Oortone May 22 '18 at 09:53
  • @Imrul, this is of course only an example. But I don't want any memory leakage however small. I need to learn how to do this the right way in Swift and I find it a bit confusing. I mean, the new scene is instanciated inside a local function. In my understanding that would mean the instance is destroyed when the function exits but that's obviously not the case and that's why I suspect it leads to memory leakage should the scenes change often. But I will definitley read your link to learn more. – Oortone May 22 '18 at 09:54
  • @KnightOf Dragon, I can not override deinit. Compiler says: "Method does not override any method in superclass". Also I'm not allowed to use deinit as a keyword if I write the function without override. So I don't know how to call any method when object is deinitialized. – Oortone May 22 '18 at 10:30
  • @Oortone copy/paste this into GameScene: `deinit { print("deinit") }` – 0x141E May 22 '18 at 18:51
  • @Oortone I got the same issue, do you found how to solve it? – Serhii Didanov Jan 30 '19 at 09:12

0 Answers0