SwiftUI App resets SKScene after becoming active again

266 views Asked by At

Every time my app goes into the background and then becomes active again, SpriteView always resets and the SKScene goes back to the beginning of the level. How can I stop this or what am I doing wrong?

My Code:

struct GameContainer: View {

    private var scene: SKScene {
        let scene = Splash()
        scene.size = Size.shared.setupSceneSize()
        scene.scaleMode = .aspectFit
        return scene
    }  

    var body: some View {
        SpriteView(scene: scene, options: .ignoresSiblingOrder)
            .edgesIgnoringSafeArea(.all)
            .statusBar(hidden: true)
    }
}

struct Game: View {

    ...

    var body: some View {
        NavigationView {
            ZStack {
                GameContainer()
                ....

Update:

struct GameContainer: View {

    static var scene = Splash()

    var body: some View {
        SpriteView(scene: GameContainer.scene, options: .ignoresSiblingOrder)
            .edgesIgnoringSafeArea(.all)
            .statusBar(hidden: true)
    }
}

class Splash: SKScene {
     override init() {
         super.init(size: Size.shared.setupSceneSize())
         scaleMode = .aspectFit
     }
     ....
}
1

There are 1 answers

7
West1 On

Try setting the size and scale mode of the scene inside Splash(), then make scene static. I think that should solve the problem of the SpriteView reloading all the time.

struct GameContainer: View {

    static var scene = Splash()

    var body: some View {
        SpriteView(scene: GameContainer.scene, options: .ignoresSiblingOrder)
            .ignoresSafeArea()
            .statusBar(hidden: true)
    }
}

struct Game: View {

    ...

    var body: some View {
        NavigationView {
            ZStack {
                GameContainer()
                ....