Connecting GameScene.swift to GameViewController.swift

Hi! I'm trying to connect GameScene.swift to GameViewController.swift.

In GameScene I have this function:


func pause() {
}


That works correctly and the game gets paused.

Then, in my View Controller, I added a button of pause. What I want is to call pause() when the button is pressed. I tried adding this to the GameViewController.swift:


@IBOutlet var PauseButton: UIButton!
@IBAction func PauseButton(_ sender: UIButton) {
        let gameScene = GameScene()
        gameScene.pause()
}


But it doesn't do anything when I press the button. The Outlet and the Action are connected well and everything else in the game works good.

Could anyone help me?


Thank you!


Ivet

Accepted Reply

Newly instatiated GemeScene cannot be the same instance as the GameViewController is currently showing.


You may need to write something like this:

    @IBAction func pauseButton(_ sender: UIButton) {
        if
            let view = self.view as! SKView?,
            let gameScene = view.scene as? GameScene
        {
            gameScene.pause()
            //...
        }
    }


(You should better follow the simple convention of Swift, property names or method names do not start with Capital letter.)

Replies

Newly instatiated GemeScene cannot be the same instance as the GameViewController is currently showing.


You may need to write something like this:

    @IBAction func pauseButton(_ sender: UIButton) {
        if
            let view = self.view as! SKView?,
            let gameScene = view.scene as? GameScene
        {
            gameScene.pause()
            //...
        }
    }


(You should better follow the simple convention of Swift, property names or method names do not start with Capital letter.)