Swift: Deallocate GameScene after transition to new scene?

后端 未结 1 1124
一向
一向 2021-02-09 23:29

So I\'ve read several questions on this but most are in Objective-C and I haven\'t found any that address/answer this directly. I am new to programming here so please explain a

相关标签:
1条回答
  • 2021-02-10 00:08

    In my project, I used the following mechanism and it worked well. All my scenes SKScene objects were optional variables. When i need the new scene to show, i create it and present at SKView. When i need to display the new scene, I set the previous object scene object to nil, this immediately reducing the reference count by 1, and becouse of at this moment no one object is not use my scene, the reference count becomes zero and scene was deleted.

    The SKScene object is a ordinary class object and ARC works with them like with all reference type objects. You only need to monitor the number of references to the scene. All are finished with the various resources I was start in deinit of SKScene object

    The simple example:

    At UIViewController we have optional objects of GameScene:

    class GameViewController: UIViewController {
        var scene1: GameScene?
        var scene2: GameScene?
        var skView: SKView?
        
        // Action to present next Scene
        @IBAction func nextSceneAction(sender: AnyObject) {
            print("Next scene")
            // Create new GameScene object
            scene2 = GameScene(fileNamed:"GameScene")
            // Present scene2 object that replace the scene1 object
            skView!.presentScene(scene2)
            scene = nil
        }
        
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // Create GameScene object
            scene = GameScene(fileNamed:"GameScene")
            skView = (self.view as! SKView)
            skView!.showsFPS = true
            skView!.showsNodeCount = true
    
            skView!.ignoresSiblingOrder = true
            
            scene!.scaleMode = .AspectFill
            
            // Present current scene
            skView!.presentScene(scene)
        }
    }
    

    At GameScene in deinit print some text to show that it object will be deleted:

    class GameScene: SKScene {
       ...
        
        deinit {
            print("Deinit scene")
        }
    }
    

    Debug output after push the nextSceneAction button:

    Next scene

    Deinit scene

    0 讨论(0)
提交回复
热议问题