从AppDelegate调用GameScene方法(Swift 3,SpriteKit,Xcode 8) [英] Call GameScene method from AppDelegate (Swift 3, SpriteKit, Xcode 8)
问题描述
我正在使用Spritekit和swift 3来创建游戏,我的问题是当我尝试从applicationWillResignActive(_ application: UIApplication)
方法中的AppDelegate文件调用GameScene类(SKScene的子类)中存在的pauseGame()
方法时./p>
我已经尝试实例化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()
}
I am using Spritekit and swift 3 for create a game, my problem is when I try to call my pauseGame()
method, present in my GameScene class (subclass of SKScene), from AppDelegate file within applicationWillResignActive(_ application: UIApplication)
method.
I already try to instantiate GameScene class and then call the method in my AppDelegate file in this way, although there is no compiler error it doesn't work:
func applicationWillResignActive(_ application: UIApplication) {
if let gameScene = GameScene(fileNamed: "GameScene") {
gameScene.pauseGame()
}
}
How can I resolve this? Thanks in advance.
You are creating a new instance of your GameScene. To pause the existing instance you need to add a reference to it in the AppDelegate.
The better solution it to register the GameScene class to receive notifications when the app goes into the background. This is a good alternative to coupling these classes with the AppDelegate.
In your GameScene class add this in the viewDidLoad() function:
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)
Add this function to the GameScene class to react to the received notification:
func applicationWillResignActive(notification: NSNotification) {
pauseGame()
}
这篇关于从AppDelegate调用GameScene方法(Swift 3,SpriteKit,Xcode 8)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!