I am trying to use the isPaused:
argument in the SpriteView
initializer to pause the SKScene
when a state property changes in SwiftUI.
@State private var showingLevelChooser = false
var body: some View {
SpriteView(scene: scene, isPaused: showingLevelChooser)
}
But when I use the state variable like:
SpriteView(scene: scene, isPaused: showingLevelChooser)
instead of just:
SpriteView(scene: scene)
the SKScene is recreated every time the variable changes, which is not what I want. I only want to pause the game.
As far as I understand this happens because SwiftUI recreates the views that are dependent on the state.
But if this is the case, how can you pause the SpriteKit scene from SwiftUI, without reinitializing it every time?
I created a sample Xcode 13 project here: https://github.com/clns/SpriteView-isPaused
The SKScene
is displaying the time elapsed on the screen, in seconds. Every time the SwiftUI sheet is presented and the state variable changes, the timer starts from 0 (zero), because the scene is recreated.
A preview is included in the GitHub project. I cannot upload an animated gif here.