从AppDelegate调用GameScene方法(Swift 3,SpriteKit,Xcode 8)
我使用Spritekit和SWIFT 3来创build游戏,我的问题是当我尝试从applicationWillResignActive(_ application: UIApplication)
方法的AppDelegate文件中调用我的GameScene类(SKScene的子类)中的pauseGame applicationWillResignActive(_ application: UIApplication)
方法。
我已经尝试实例化GameScene类,然后以这种方式调用我的AppDelegate文件中的方法,虽然没有编译器错误它不起作用:
func applicationWillResignActive(_ application: UIApplication) { if let gameScene = GameScene(fileNamed: "GameScene") { gameScene.pauseGame() } }
我该如何解决这个问题? 提前致谢。
您正在创buildGameScene的新实例。 要暂停现有的实例,您需要在AppDelegate中添加对其的引用。
更好的解决scheme来注册GameScene类来接收通知,当应用程序进入后台。 这是将这些类与AppDelegate耦合的一个很好的select。
在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() }