How to call method from ViewController in GameScene

后端 未结 4 869
遇见更好的自我
遇见更好的自我 2020-12-01 13:21

I have a method that has a custom segue in my viewController that looks like this:

func gameOver() {
    performSegueWithIdentifier(\"GameOver\", sender: nil         


        
4条回答
  •  日久生厌
    2020-12-01 13:45

    I don't know if this is still relevant, but I would like to present you a solution to this problem.

    As you can see here Swift iOS: Perform a Segue from an Instance in a ViewController to another ViewController I had the exact same problem some time ago, which I managed to fix using Protocols.

    The problem is, that you can call the "performSegueWithIdentifier("GameOver", sender: nil)" only in your GameViewController Class, but you would like to execute it from your Gamescene.

    Therefor you create in your GameScene a protocol like this:

    @objc protocol GameOverDelegate {
      func gameOverDelegateFunc()
    }
    

    and a variable for the delegate in the Gamescene:

    var gamescene_delegate : GameOverDelegate?
    

    in your GameViewController Class you have to add the delegate in the class definition

    class GameViewController: UIViewController, GameOverDelegate {
    ...
    }
    

    and set the delegate of the scene in the viewDidLoad function of your GameViewController to self:

    scene.gamescene_delegate = self
    

    The last step is to implement the gameOverDelegateFunc() function in your GameViewController:

    func gameOverDelegateFunc() {
       self.performSegueWithIdentifier("GameOver", sender: nil)
    }
    

    This is all you have to do.

    Whenever you want to perform this Segue in your GameScene you just have to call the function through the delegate like this:

    gamescene_delegate?.gameOverDelegateFunc()
    

    I hope that everything is clear and I could help,

    Regards, Phil

提交回复
热议问题