簡體   English   中英

從AppDelegate調用GameScene方法(Swift 3,SpriteKit,Xcode 8)

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

我正在使用Spritekit和swift 3來創建一個游戲,我的問題是當我嘗試調用我的pauseGame()類(來自SKScene的子類)時,從applicationWillResignActive(_ application: UIApplication)方法中的AppDelegate文件中調用我的pauseGame() 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()
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM