I have two simple scenes. One is a Game Scene and the other is a Game Over Scene:
class TestGameScene: SKScene {
override init(size: CGSize) {
super.init(size: size)
print("Initialising Test Game Scene \(ObjectIdentifier(self))")
let textNode = SKLabelNode(text: "Game Scene")
textNode.position.x = frame.midX
textNode.position.y = frame.midY
addChild(textNode)
}
// required init omitted for clarity ...
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view!.presentScene(TestGameOverScene(size: size))
}
}
class TestGameOverScene: SKScene {
override init(size: CGSize) {
super.init(size: size)
print("Initialising Game Over Scene \(ObjectIdentifier(self))")
let textNode = SKLabelNode(text: "Game Over")
textNode.position.x = frame.midX
textNode.position.y = frame.midY
addChild(textNode)
}
// required init omitted for clarity ...
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view!.presentScene(TestGameScene(size: size))
}
}
and I display the scene using a simple SpriteView
struct ContentView: View {
var body: some View {
SpriteView(scene: TestGameScene(size: CGSize(width: 300, height: 300)))
}
}
From within the TestGameScene
I want to present the TestGameOverScene
when the user touches the screen. This works as expected except when I make the app go into the background. When the app goes into the background as the TestGameOverScene
is visible, the TestGameOverScene
deinitialises for some reason. This causes the original TestGameScene
to move to the view again.
I initially thought SwiftUI was recomputing the body
property or something but it turns out that it wasn't. The issue has got to do with something else that I can't figure out.
What's the correct way to transition between scenes without unnecessarily keeping both scenes in memory? I want one to deinitialise when the other is transitioned to. Or does SpriteView
simply not support this sort of thing? Any advice would be appreciated.