从 AppDelegate 调用 GameScene 方法 (Swift 3, SpriteKit, Xcode 8)

Call GameScene method from AppDelegate (Swift 3, SpriteKit, Xcode 8)

我正在使用 Spritekit 和 swift 3 创建游戏,我的问题是当我尝试调用我的 pauseGame() 方法时,出现在我的 GameScene class (sub[= SKScene 的 21=]),来自 applicationWillResignActive(_ application: UIApplication) 方法中的 AppDelegate 文件。

我已经尝试实例化 GameScene class 然后以这种方式调用我的 AppDelegate 文件中的方法,虽然没有编译错误但它不起作用:

func applicationWillResignActive(_ application: UIApplication) {

    if let gameScene = GameScene(fileNamed: "GameScene") {

        gameScene.pauseGame()
    }
}

我该如何解决这个问题?提前致谢。

您正在创建 GameScene 的新实例。 要暂停现有实例,您需要在 AppDelegate 中添加对它的引用。

更好的解决方案是注册 GameScene class 以在应用进入后台时接收通知。这是将这些 classes 与 AppDelegate 耦合的一个很好的替代方法。

在您的 GameScene class 中将此添加到 viewDidLoad() 函数中:

let app = UIApplication.shared

//Register for the applicationWillResignActive anywhere in your app.
NotificationCenter.default.addObserver(self, selector: #selector(GameScene.applicationWillResignActive(notification:)), name: NSNotification.Name.UIApplicationWillResignActive, object: app)

将此函数添加到 GameScene class 以对收到的通知做出反应:

func applicationWillResignActive(notification: NSNotification) {
     pauseGame()
}