从 AppDelegate 调用 GameScene 方法(Swift 3、SpriteKit、Xcode 8) [英] Call GameScene method from AppDelegate (Swift 3, SpriteKit, Xcode 8)

查看:21
本文介绍了从 AppDelegate 调用 GameScene 方法(Swift 3、SpriteKit、Xcode 8)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Spritekit 和 swift 3 来创建游戏,我的问题是当我尝试从 AppDelegate 文件调用我的 GameScene 类(SKScene 的子类)中的 pauseGame() 方法时在 applicationWillResignActive(_ application: UIApplication) 方法中.

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.

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

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.

推荐答案

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

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.

更好的解决方案是注册 GameScene 类以在应用程序进入后台时接收通知.这是将这些类与 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.

在您的 GameScene 类中,将其添加到 viewDidLoad() 函数中:

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)

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆