我使用Spritekit快捷3创建一个游戏,我的问题是,当我尝试打电话给我pauseGame()
内的方法,存在于我的GameScene类(SKScene的子类),从AppDelegate中文件applicationWillResignActive(_ application: UIApplication)
方法。
我已经尝试实例化GameScene类,然后调用该方法以这种方式我的AppDelegate文件,虽然没有编译器错误它不工作:
func applicationWillResignActive(_ application: UIApplication) {
if let gameScene = GameScene(fileNamed: "GameScene") {
gameScene.pauseGame()
}
}
我怎样才能解决这个问题? 提前致谢。
您正在创建您的GameScene的新实例。 要暂停现有的情况下,你需要参考在AppDelegate中添加到它。
较好的解决它注册GameScene类,当应用程序进入后台接收通知。 这是这些类与AppDelegate中耦合一个很好的选择。
在您的GameScene类添加这个在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类要接收的通知做出反应:
func applicationWillResignActive(notification: NSNotification) {
pauseGame()
}